基本网上copy烂了的,就是有些需要注意的,加了些注释,直接上代码
node代码
var assert = require('assert');
var crypto = require('crypto');
function test_des(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var plaintext = param.plaintext
var alg = param.alg
var autoPad = param.autoPad
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad) //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex'); //自己项目为base64,所以hex改为base64,下面一样
ciph += cipher.final('hex');
console.log(alg, ciph)
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad)
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');
assert.equal(txt, plaintext, 'fail');
}
test_des({
alg: 'des-ede3', //3des-ecb
autoPad: true,
key: '0123456789abcd0123456789', //3des即为3重des,所以秘钥为3*8 24字节,如果对接文档超过24,可能java部分转换秘钥会自动截取,以下java部分有相应注释
plaintext: '1234567812345678',
iv: null
})
test_des({
alg: 'des-ede3-cbc', //3des-cbc
autoPad: true,
key: '0123456789abcd0123456789',
plaintext: '1234567812345678',
iv: '12345678'
})
Java代码
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.junit.Test;
@Test
public void encrypt_3des_ecb() throws Exception {
byte[] key = "0123456789abcd0123456789".getBytes();
byte[] plainText = "1234567812345678".getBytes();
//若使用以下三行代码工厂方式转换秘钥,注意,key的长度超过24的话生成的myMykeySpec对象 为key自动截取的前24位
// KeySpec myKeySpec = new DESedeKeySpec(key);
// SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance("DESede");
// SecretKey secretKey = mySecretKeyFactory.generateSecret(myKeySpec);
SecretKey secretKey = new SecretKeySpec(key, "DESede"); //3des使用此种方式key长度固定24
//encrypt
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(plainText);
System.out.println("encrypt_3des_ecb: " + Hex.encodeHexString(encryptedData));
//decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptPlainText = cipher.doFinal(encryptedData);
org.junit.Assert.assertArrayEquals(decryptPlainText, plainText);
}
@Test
public void encrypt_3des_cbc() throws Exception {
byte[] key = "0123456789abcd0123456789".getBytes();
byte[] plainText = "1234567812345678".getBytes();
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
SecretKey secretKey = new SecretKeySpec(key, "DESede");
//encrypt
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encryptedData = cipher.doFinal(plainText);
System.out.println("encrypt_3des_cbc: " + Hex.encodeHexString(encryptedData));
//decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] decryptPlainText = cipher.doFinal(encryptedData);
org.junit.Assert.assertArrayEquals(decryptPlainText, plainText);
}