在多语言的生产环境下,常常是由一种语言进行加密而由另一种语言来进行解密,因此有必要保持各种语言之间加密解密算法的一致性。下面列出了Go,Nodejs,Java 的 Aes-128-Ecb的加密解密算法,它们的加解密结果是一致的。需要指出的是由于Nodejs对key做了md5计算,所以Golang和Java也需要对应加入key的md5计算。
Go 1.15
package main
import (
"crypto/aes"
"crypto/md5"
"encoding/hex"
"fmt"
)
func generateMd5Key(str string) []byte {
checksum := md5.Sum([]byte(str))
return checksum[0:]
}
func aesEncryptECB(plaintext string, key string) string {
origData := []byte(plaintext)
checksum := generateMd5Key(key)
cipher, _ := aes.NewCipher(checksum)
length := (len(origData) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, origData)
pad := byte(len(plain) - len(origData))
for i := len(origData); i < len(plain); i++ {
plain[i] = pad
}
encrypted := make([]byte, len(plain))
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
}
return hex.EncodeToString(encrypted)
}
func aesDecryptECB(ciphertext string, key string) (string, error) {
checksum := generateMd5Key(key)
cipher, _ := aes.NewCipher(checksum)
encrypted, err := hex.DecodeString(ciphertext)
if err != nil {
return "", err
}
decrypted := make([]byte, len(encrypted))
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
}
trim := 0
if len(decrypted) > 0 {
trim = len(decrypted) - int(decrypted[len(decrypted)-1])
}
return string(decrypted[:trim]), nil
}
func main() {
key := "sykKw59_q11"
plaintext := "C80E77ED1152"
fmt.Printf("原 文:%s\n", plaintext)
encrypted := aesEncryptECB(plaintext, key)
fmt.Printf("加密结果:%s\n", encrypted)
decrypted, err := aesDecryptECB(encrypted, key)
if err != nil {
panic(err)
}
fmt.Printf("解密结果:%s\n", decrypted)
}
nodejs 8.16
/**
* * aes加密
* * @param data
* * @param secretKey
* */
aesEncrypt = function(data, secretKey) {
var cipher = crypto.createCipher('aes-128-ecb', secretKey);
return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
}
/**
* * aes解密
* * @param data
* * @param secretKey
* * @returns {*}
* */
aesDecrypt = function(data, secretKey) {
var cipher = crypto.createDecipher('aes-128-ecb', secretKey);
return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8');
}
//console.log(aesEncrypt("C80E77ED1152", "sykKwe59_q11peDz"));
let key = "sykKw59_q11";
let plaintext = "C80E77ED1152";
console.log("原 文:" + plaintext);
let encrypted = aesEncrypt(plaintext, key);
console.log("加密结果:" + encrypted);
console.log("解密结果:" + aesDecrypt(encrypted, key));
java 1.8
package com.basic;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密,与Nodejs 保持一致
*
* @author lmiky
* @date 2014-2-25
*/
public class AesEcb {
public static final String DEFAULT_CODING = "utf-8";
/**
* 解密
*
* @author lmiky
* @date 2014-2-25
* @param encrypted
* @param seed
* @return
* @throws Exception
*/
private static String decrypt(String encrypted, String seed) throws Exception {
byte[] keyb = seed.getBytes(DEFAULT_CODING);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keyb);
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
Cipher dcipher = Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, skey);
byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
return new String(clearbyte);
}
/**
* 加密
*
* @author lmiky
* @date 2014-2-25
* @param content
* @param key
* @return
* @throws Exception
*/
public static String encrypt(String content, String key) throws Exception {
byte[] input = content.getBytes(DEFAULT_CODING);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return parseByte2HexStr(cipherText);
}
/**
* 字符串转字节数组
*
* @author lmiky
* @date 2014-2-25
* @param hexString
* @return
*/
private static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++) {
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
}
return result;
}
/**
* 字节转16进制数组
*
* @author lmiky
* @date 2014-2-25
* @param buf
* @return
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex);
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String key = "sykKw59_q11";
String plaintext = "C80E77ED1152";
System.out.println("原 文:" + plaintext);
String encrypted = encrypt(plaintext, key);
System.out.println("加密结果:" + encrypted);
System.out.println("解密结果:" + decrypt(encrypted, key));
}
}
输出:
原 文:C80E77ED1152
加密结果:835748c230cbd352843fcabfd67415f2
解密结果:C80E77ED1152
相关文章:
《Go Nodejs Java Aes 128 CBC 加密解密结果保持一致》
参考文章:
《nodejs和java的AES加密结果保持一致》
《golang的AES加密和解密的三种模式实现(CBC/ECB/CFB)》