Exception in thread "main" java.security.InvalidKeyException: Wrong key size
Exception in thread "main" java.security.InvalidKeyException: 6 length 。。(忘了是啥了)
出現以上異常注意啦:
DES加密,只允許密鑰是8個字節的。
AES加密,密鑰必須是16個字節的.
也就是說 key=“12345678”可以,key="123456789"就會報錯。
DES
public static void main(String[] args) throws Exception{
//
//原文
String input = "硅谷";
//定義key
//使用DEs 密鑰必須是8個字節
String key = "12345611";
//算法
String transformation = "DES";
//加密類型
String algorithm = "DES";
//創建加密對像
Cipher cipher=Cipher.getInstance(transformation);
//創建加密規則
//第一個參數:key的字節碼 第二個參數:加密類型
SecretKeySpec secretKeySpec =new SecretKeySpec(key.getBytes(),algorithm);
//加密初始化
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
//調用加密方法
byte[] bytes=cipher.doFinal(input.getBytes());
// 查看密文
System.out.println(new String(bytes));
}
AES
public static void main(String[] args) throws Exception{
//
//原文
String input = "硅谷";
//定義key
//使用DEs 密鑰必須是8個字節
//使用AES 密鑰必須是16個字節
String key = "1234561112345678";
//算法
String transformation = "AES";
//加密類型
String algorithm = "AES";
//創建加密對像
Cipher cipher=Cipher.getInstance(transformation);
//創建加密規則
//第一個參數:key的字節碼 第二個參數:加密類型
SecretKeySpec secretKeySpec =new SecretKeySpec(key.getBytes(),algorithm);
//加密初始化
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
//調用加密方法
byte[] bytes=cipher.doFinal(input.getBytes());
// 查看密文
System.out.println(new String(bytes));
}
RSA
public static void main(String[] args) throws Exception {
String input = "阿拉蕾";
String algorithm = "RSA";
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance(algorithm);
//生成密鑰對
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//生成公鑰
PublicKey publicKey = keyPair.getPublic();
//生成私鑰
PrivateKey privateKey = keyPair.getPrivate();
//獲取字節數組
byte[] privateencoded = privateKey.getEncoded();
byte[] publicencoded = publicKey.getEncoded();
// 使用base64 轉碼
String privateKeyEncoded = String.valueOf(Base64.encode(privateencoded));
String publicKeyEncoded = String.valueOf(Base64.encode(publicencoded));
//打印
System.out.println(privateKeyEncoded);
System.out.println(publicKeyEncoded);
//創建加密方式
Cipher cipher = Cipher.getInstance(algorithm);
//密匙加密
cipher.init(Cipher.ENCRYPT_MODE,privateKey);
byte[] bytes = cipher.doFinal(input.getBytes());
System.out.println("加密轉碼:"+Base64.encode(bytes));
//公鑰解密
cipher.init(Cipher.DECRYPT_MODE,publicKey);
byte[] bytes1 = cipher.doFinal(bytes);
//注意解碼用 new String()方法裝字節數組
System.out.println("解密:"+new String(bytes1));
}
