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)); }