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
+41.2k Golang : How to count duplicate items in slice/array?
+24.6k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+9.4k Golang : Play .WAV file from command line
+12.7k Golang : Remove or trim extra comma from CSV
+15.6k Golang : How to convert(cast) IP address to string?
+15.9k Golang : Get file permission
+5.7k Unix/Linux/MacOSx : Get local IP address
+14.3k Golang : Simple word wrap or line breaking example
+9.4k Golang : Create unique title slugs example
+8.7k Golang : Combine slices but preserve order example
+24.5k Golang : GORM read from database example
+7.5k Golang : Dealing with struct's private part