Skip to content

Instantly share code, notes, and snippets.

@zdev0x
Last active January 24, 2024 08:18
Show Gist options
  • Select an option

  • Save zdev0x/a18ae1ab34c5df44301c80d280552ac5 to your computer and use it in GitHub Desktop.

Select an option

Save zdev0x/a18ae1ab34c5df44301c80d280552ac5 to your computer and use it in GitHub Desktop.
aes-256-cbc encryption and decryption interoperability (php/golang)
<?php
class CryptHelper
{
const CIPHER_ALGO = 'AES-256-CBC';
/**
* 加密
* @param $plaintext
* @param $password
* @return string
*/
public static function encrypt($plaintext, $password)
{
$method = self::CIPHER_ALGO;
$key = md5($password);
$iv = substr($key, 0, 16);
// OPENSSL_RAW_DATA = 1
$ciphertext = openssl_encrypt($plaintext, $method, $key, 1, $iv);
return bin2hex($ciphertext);
}
/**
* @param $hexData
* @param $password
* @return false|string
*/
public static function decrypt($hexData, $password)
{
$method = self::CIPHER_ALGO;
// 兼容php5.3
$data = pack('H*', $hexData);
// $data = hex2bin($hexData);
$key = md5($password);
$iv = substr($key, 0, 16);
return openssl_decrypt($data, $method, $key, 1, $iv);
}
}
package xcrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/hex"
"errors"
)
func Encrypt(plaintext string, password string) (string, error) {
pass := md5V(password)
keyBytes := []byte(pass)
key := keyBytes[:]
iv := key[:16]
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
paddedPlaintext := pkcs5Padding([]byte(plaintext), block.BlockSize())
mode := cipher.NewCBCEncrypter(block, iv)
ciphertext := make([]byte, len(paddedPlaintext))
mode.CryptBlocks(ciphertext, paddedPlaintext)
return hex.EncodeToString(ciphertext), nil
}
func Decrypt(hexData string, password string) (string, error) {
data, err := hex.DecodeString(hexData)
if err != nil {
return "", err
}
pass := md5V(password)
keyBytes := []byte(pass)
key := keyBytes[:]
iv := key[:16]
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(data) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(data, data)
return string(pkcs5UnPadding(data)), nil
}
func pkcs5UnPadding(data []byte) []byte {
length := len(data)
unpadding := int(data[length-1])
return data[:(length - unpadding)]
}
func md5V(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment