Skip to content

Instantly share code, notes, and snippets.

@Eiryyy
Created July 11, 2018 06:00
Show Gist options
  • Select an option

  • Save Eiryyy/a5b74691dbd978c6c530c18c127730ca to your computer and use it in GitHub Desktop.

Select an option

Save Eiryyy/a5b74691dbd978c6c530c18c127730ca to your computer and use it in GitHub Desktop.
AES-256-CBC Encrypt: Go / Node.js
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...)
}
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