对称加密算法 之 3DES 篇
密钥长度 |
默认 |
工作模式 |
填充方式 |
实现方式 |
112、168 | 168 |
ECB、CBC、PCBC、CTR、CTS、CFB、CFB8到128、OFB、OFB8到128 |
NoPdding、PKCS5Padding、ISO10126Padding |
JDK |
128、192 |
168 | 同上 |
PKCS7Padding、ISO10126d2Padding、X932Padding、ISO7816d4Padding、ZeroBytePadding |
BC |
package com.baikeyang;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
/**
* Created by lenovo on 2016/12/28.
*/
public class ThreeDESEncryption {
public static void main (String[] args) {
// 3重DES
jdk3DES();
}
static String str = "你好,中国";
private static void jdk3DES() {
try {
// 生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
//keyGenerator.init(168);
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded();
// KEY转换
DESedeKeySpec desKeySpec = new DESedeKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
Key convertSecretKey = factory.generateSecret(desKeySpec);
// 加密
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] result = cipher.doFinal(str.getBytes());
System.out.println("JDK des encrypt " + new String(Hex.encodeHex(result)));
// 解密
cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
result = cipher.doFinal(result);
System.out.println("JDK des decrypt " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
}