-
-
Save PierreZ/56a7e8c95c4131997048b24be37d9a61 to your computer and use it in GitHub Desktop.
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 ( | |
"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(fmt.Printf("%X", encrypted)) | |
fmt.Println(base64.URLEncoding.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