Golang crypto/rc4.NewCipher() function example
package crypto/rc4
NewCipher creates and returns a new Cipher. The key argument should be the RC4 key, at least 1 byte and at most 256 bytes.
Golang crypto/rc4.NewCipher() function usage example
package main
import (
"crypto/rc4"
"fmt"
)
func main() {
key := []byte("123") // min 1 byte, max is 256 bytes!
c, err := rc4.NewCipher(key)
if err != nil {
// this is the KeySizeError output if the key is less than 1 byte
// or more than 256 bytes
fmt.Println(err.Error) // KeySizeError
}
plaintext := []byte("Secret message")
//encrypt
encrypted := make([]byte, len(plaintext))
c.XORKeyStream(encrypted, plaintext)
fmt.Printf("[%s] encrypted to [%x] by rc4 crypto\n", plaintext, encrypted)
c.Reset() // reset the key data just for fun
//decrypt
decrypted := make([]byte, len(encrypted))
// we need to generate back the key because it was Reset above
c, err = rc4.NewCipher(key)
if err != nil {
fmt.Println(err.Error)
}
c.XORKeyStream(decrypted, encrypted)
fmt.Printf("[%x] decrypted to [%s] \n", encrypted, decrypted)
}
Sample output :
go run cryptorc4.go
[Secret message] encrypted to [0095dcf080002496401070eb197e] by rc4 crypto
[0095dcf080002496401070eb197e] decrypted to [Secret message]
Reference :
http://golang.org/pkg/crypto/rc4/#NewCipher
Advertisement
Something interesting
Tutorials
+9.4k Golang : Find the length of big.Int variable example
+10.7k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+8.3k Golang : Count leading or ending zeros(any item of interest) example
+9.8k Golang : Format strings to SEO friendly URL example
+5.9k Golang : Use NLP to get sentences for each paragraph example
+7.7k Golang : Error reading timestamp with GORM or SQL driver
+11.9k Golang : How to parse plain email text and process email header?
+5.4k Javascript : How to loop over and parse JSON data?
+13.1k Golang : Convert(cast) uintptr to string example
+5.6k Unix/Linux : How to find out the hard disk size?
+11.6k SSL : The certificate is not trusted because no issuer chain was provided
+7.2k Golang : Dealing with postal or zip code example