Last active
August 29, 2015 14:18
-
-
Save zgiber/6f8198342ea7da69cb5d to your computer and use it in GitHub Desktop.
AES Encryption and Decryption in GO
This file contains 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
package main | |
import ( | |
"crypto/aes" | |
"crypto/cipher" | |
"crypto/rand" | |
"crypto/sha256" | |
"fmt" | |
"io" | |
) | |
const SECRET = "Hello This is a new secret! Now even longer" | |
func main() { | |
encryptedData, _ := encrypt("Testing AES encryption!") | |
fmt.Printf("%x \n", encryptedData) | |
result, _ := decrypt(encryptedData) | |
fmt.Printf("%s\n", result) | |
} | |
func encrypt(text string) ([]byte, error) { | |
key := sha256.Sum256([]byte(SECRET)) | |
block, err := aes.NewCipher(key[:]) | |
if err != nil { | |
return nil, err | |
} | |
fmt.Printf("%d bytes NewCipher key with block size of %d bytes\n", len(key), block.BlockSize()) | |
cipherText := make([]byte, len(text)+aes.BlockSize) | |
iv := cipherText[:aes.BlockSize] | |
if _, err = io.ReadFull(rand.Reader, iv); err != nil { | |
return nil, err | |
} | |
fmt.Printf("IV: %x\n", iv) | |
enc := cipher.NewCFBEncrypter(block, iv) | |
enc.XORKeyStream(cipherText[aes.BlockSize:], []byte(text)) | |
return cipherText, nil | |
} | |
func decrypt(cipherData []byte) (string, error) { | |
key := sha256.Sum256([]byte(SECRET)) | |
block, err := aes.NewCipher(key[:]) | |
if err != nil { | |
return "", err | |
} | |
if len(cipherData) < aes.BlockSize { | |
return "", fmt.Errorf("Invalid text") | |
} | |
data := cipherData[aes.BlockSize:] | |
iv := cipherData[:aes.BlockSize] | |
cfb := cipher.NewCFBDecrypter(block, iv) | |
cfb.XORKeyStream(data, data) | |
return string(data), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment