Last active
June 5, 2019 01:24
-
-
Save kemadz/9df51d7c23abc2e60904cc77c547b834 to your computer and use it in GitHub Desktop.
aes sample code
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
var aesjs = require('aes-js') | |
var key = Buffer.from('abcdef1234fedcba') | |
var iv = aesjs.utils.utf8.toBytes(key) | |
var text = '1111222233334444' | |
var textBytes = aesjs.utils.utf8.toBytes(text) | |
// pkcs5 is a subset of pkcs7 | |
var padded = aesjs.padding.pkcs7.pad(textBytes) | |
var aesCbc = new aesjs.ModeOfOperation.cbc(iv, iv) | |
var encryptedBytes = aesCbc.encrypt(padded); | |
console.log(Buffer.from(encryptedBytes).toString('base64')) |
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 ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"encoding/base64" | |
"fmt" | |
"net/url" | |
) | |
var Key = []byte("abcdef1234fedcba") | |
func main() { | |
src := "1111222233334444" | |
encrypted := AESEncrypt(src, Key) | |
fmt.Println(url.QueryEscape(base64.StdEncoding.EncodeToString(encrypted))) | |
decrypted := AESDecrypt(encrypted, Key) | |
fmt.Println(string(decrypted)) | |
} | |
func AESEncrypt(src string, key []byte) []byte { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println("key error1", err) | |
} | |
if src == "" { | |
fmt.Println("plain content empty") | |
} | |
ecb := cipher.NewCBCEncrypter(block, Key) | |
content := []byte(src) | |
content = PKCS5Padding(content, block.BlockSize()) | |
crypted := make([]byte, len(content)) | |
ecb.CryptBlocks(crypted, content) | |
return crypted | |
} | |
func AESDecrypt(crypt []byte, key []byte) []byte { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println("key error1", err) | |
} | |
if len(crypt) == 0 { | |
fmt.Println("plain content empty") | |
} | |
ecb := cipher.NewCBCDecrypter(block, Key) | |
decrypted := make([]byte, len(crypt)) | |
ecb.CryptBlocks(decrypted, crypt) | |
return PKCS5Trimming(decrypted) | |
} | |
func PKCS5Padding(ciphertext []byte, blockSize int) []byte { | |
padding := blockSize - len(ciphertext)%blockSize | |
padtext := bytes.Repeat([]byte{byte(padding)}, padding) | |
return append(ciphertext, padtext...) | |
} | |
func PKCS5Trimming(encrypt []byte) []byte { | |
padding := encrypt[len(encrypt)-1] | |
return encrypt[:len(encrypt)-int(padding)] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment