Skip to content

Instantly share code, notes, and snippets.

@PierreZ
Created September 22, 2016 17:57
Show Gist options
  • Save PierreZ/c057ef3a1ab1a18328cf6967a46b359f to your computer and use it in GitHub Desktop.
Save PierreZ/c057ef3a1ab1a18328cf6967a46b359f to your computer and use it in GitHub Desktop.
aes wrap
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
)
// Appends padding.
func pkcs7Pad(data []byte, blocklen int) ([]byte, error) {
if blocklen <= 0 {
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
}
padlen := 1
for ((len(data) + padlen) % blocklen) != 0 {
padlen = padlen + 1
}
pad := bytes.Repeat([]byte{byte(padlen)}, padlen)
return append(data, pad...), nil
}
func main() {
key := []byte("cfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcf")
originalText := []byte("{\"token\":\"Token\",\"limit\":\"1000\"}")
data, err := GenerateRandomBytes(8)
if err != nil {
fmt.Println(err)
}
data = append(data, originalText...)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
padded, err := pkcs7Pad(data, block.BlockSize())
encrypted := make([]byte, len(padded))
iv := padded[:block.BlockSize()] // const BlockSize = 8
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(encrypted, padded)
fmt.Println(base64.RawStdEncoding.EncodeToString(encrypted))
}
// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment