-
-
Save ferronrsmith/854538b2506f32b7d031c4d3991423d4 to your computer and use it in GitHub Desktop.
Golang Encrypt Decrypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Refrence http://stackoverflow.com/questions/18817336/golang-encrypting-a-string-with-aes-and-base64 | |
package main | |
import ( | |
"crypto/aes" | |
"crypto/cipher" | |
"crypto/rand" | |
"encoding/base64" | |
"errors" | |
"fmt" | |
"io" | |
"log" | |
) | |
func main() { | |
key := []byte("a very very very very secret key") // 32 bytes | |
plaintext := []byte("some really really really long plaintext") | |
fmt.Printf("%s\n", plaintext) | |
ciphertext, err := encrypt(key, plaintext) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%0x\n", ciphertext) | |
result, err := decrypt(key, ciphertext) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%s\n", result) | |
} | |
// See alternate IV creation from ciphertext below | |
//var iv = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05} | |
func encrypt(key, text []byte) ([]byte, error) { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
return nil, err | |
} | |
b := base64.StdEncoding.EncodeToString(text) | |
ciphertext := make([]byte, aes.BlockSize+len(b)) | |
iv := ciphertext[:aes.BlockSize] | |
if _, err := io.ReadFull(rand.Reader, iv); err != nil { | |
return nil, err | |
} | |
cfb := cipher.NewCFBEncrypter(block, iv) | |
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b)) | |
return ciphertext, nil | |
} | |
func decrypt(key, text []byte) ([]byte, error) { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
return nil, err | |
} | |
if len(text) < aes.BlockSize { | |
return nil, errors.New("ciphertext too short") | |
} | |
iv := text[:aes.BlockSize] | |
text = text[aes.BlockSize:] | |
cfb := cipher.NewCFBDecrypter(block, iv) | |
cfb.XORKeyStream(text, text) | |
data, err := base64.StdEncoding.DecodeString(string(text)) | |
if err != nil { | |
return nil, err | |
} | |
return data, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment