Created
July 11, 2018 06:00
-
-
Save Eiryyy/a5b74691dbd978c6c530c18c127730ca to your computer and use it in GitHub Desktop.
AES-256-CBC Encrypt: Go / Node.js
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 crypto | |
| import ( | |
| "bytes" | |
| "crypto/aes" | |
| "crypto/cipher" | |
| "encoding/hex" | |
| ) | |
| func Encrypt(s string) string { | |
| key, _ := hex.DecodeString("key") | |
| iv, _ := hex.DecodeString("iv") | |
| plainText := []byte(s) | |
| plainText = paddingPKCS7(plainText) | |
| encrypted := make([]byte, aes.BlockSize+len(plainText)) | |
| block, _ := aes.NewCipher(key) | |
| mode := cipher.NewCBCEncrypter(block, iv) | |
| mode.CryptBlocks(encrypted[aes.BlockSize:], plainText) | |
| encrypted = bytes.TrimLeft(encrypted, "\x00") | |
| return hex.EncodeToString(encrypted) | |
| } | |
| func paddingPKCS7(data []byte) []byte { | |
| padSize := aes.BlockSize | |
| if len(data)%aes.BlockSize != 0 { | |
| padSize = aes.BlockSize - (len(data))%aes.BlockSize | |
| } | |
| pad := bytes.Repeat([]byte{byte(padSize)}, padSize) | |
| return append(data, pad...) | |
| } |
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
| const crypto = require('crypto') | |
| function encrypt(s) { | |
| const key = Buffer.from('key', 'hex') | |
| const iv = Buffer.from('iv', 'hex') | |
| const cipher = crypto.createCipheriv('aes256', key, iv) | |
| const encrypted = cipher.update(s, 'utf8', 'hex') | |
| return encrypted + cipher.final('hex') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment