Last active
July 11, 2017 12:58
-
-
Save codehakase/99c3bc704bbb5bc9928bae7794964c85 to your computer and use it in GitHub Desktop.
A Go script with methods that encrypts and decrypts strings using the Advanced Encryption Standard (AES)
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
| package main | |
| import ( | |
| "crypto/aes" | |
| "crypto/cipher" | |
| "crypto/rand" | |
| "errors" | |
| "fmt" | |
| "io" | |
| "log" | |
| ) | |
| func main() { | |
| text := []byte("I am Codehakase") | |
| key := []byte("the-key-has-to-be-32-bytes-long!") | |
| ciphertext, err := encrypt(text, key) | |
| if err != nil { | |
| // TODO: Properly handle all errors | |
| log.Fatal(err) | |
| } | |
| fmt.Printf("%s => %x\n", text, ciphertext) | |
| plaintext, err := decrypt(ciphertext, key) | |
| if err != nil { | |
| // TODO: Properly handle error | |
| log.Fatal(err) | |
| } | |
| fmt.Printf("%x => %s\n", ciphertext, plaintext) | |
| } | |
| func encrypt(plaintext []byte, key []byte) ([]byte, error) { | |
| c, err := aes.NewCipher(key) | |
| if err != nil { | |
| return nil, err | |
| } | |
| gcm, err := cipher.NewGCM(c) | |
| if err != nil { | |
| return nil, err | |
| } | |
| nonce := make([]byte, gcm.NonceSize()) | |
| if _, err = io.ReadFull(rand.Reader, nonce); err != nil { | |
| return nil, err | |
| } | |
| return gcm.Seal(nonce, nonce, plaintext, nil), nil | |
| } | |
| func decrypt(ciphertext []byte, key []byte) ([]byte, error) { | |
| c, err := aes.NewCipher(key) | |
| if err != nil { | |
| return nil, err | |
| } | |
| gcm, err := cipher.NewGCM(c) | |
| if err != nil { | |
| return nil, err | |
| } | |
| nonceSize := gcm.NonceSize() | |
| if len(ciphertext) < nonceSize { | |
| return nil, errors.New("ciphertext too short") | |
| } | |
| nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] | |
| return gcm.Open(nil, nonce, ciphertext, nil) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment