Commit 74f41102fa4459906386b25da03c10a5c200211f

Authored by Marko Tikvić
0 parents
Exists in master

first commit

Showing 2 changed files with 71 additions and 0 deletions   Show diff stats
... ... @@ -0,0 +1 @@
  1 +### Link to the original source: [Advanced encryption and decryption](https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/09.6.html)
... ...
... ... @@ -0,0 +1,70 @@
  1 +package aes
  2 +
  3 +import (
  4 + "crypto/aes"
  5 + "crypto/cipher"
  6 + "crypto/rand"
  7 + "errors"
  8 + "io"
  9 + mrand "math/rand"
  10 + "time"
  11 +)
  12 +
  13 +const (
  14 + keySize = 32
  15 + allowedRunes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  16 +)
  17 +
  18 +// RandomKey returns a randomly generated 32 bytes long hex encoded key.
  19 +func RandomKey() (key []byte) {
  20 + mrand.Seed(time.Now().UnixNano())
  21 +
  22 + key = make([]byte, keySize)
  23 +
  24 + for i := range key {
  25 + key[i] = allowedRunes[mrand.Intn(len(allowedRunes))]
  26 + }
  27 +
  28 + return key
  29 +}
  30 +
  31 +// Encrypt encrypts plaintext with key and returns resulting bytes.
  32 +func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
  33 + c, err := aes.NewCipher(key)
  34 + if err != nil {
  35 + return nil, err
  36 + }
  37 +
  38 + gcm, err := cipher.NewGCM(c)
  39 + if err != nil {
  40 + return nil, err
  41 + }
  42 +
  43 + nonce := make([]byte, gcm.NonceSize())
  44 + if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  45 + return nil, err
  46 + }
  47 +
  48 + return gcm.Seal(nonce, nonce, plaintext, nil), nil
  49 +}
  50 +
  51 +// Decrypt decrypts ciphertext with key and returns resulting bytes.
  52 +func Decrypt(ciphertext []byte, key []byte) ([]byte, error) {
  53 + c, err := aes.NewCipher(key)
  54 + if err != nil {
  55 + return nil, err
  56 + }
  57 +
  58 + gcm, err := cipher.NewGCM(c)
  59 + if err != nil {
  60 + return nil, err
  61 + }
  62 +
  63 + nonceSize := gcm.NonceSize()
  64 + if len(ciphertext) < nonceSize {
  65 + return nil, errors.New("ciphertext too short")
  66 + }
  67 +
  68 + nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
  69 + return gcm.Open(nil, nonce, ciphertext, nil)
  70 +}
... ...