importjava.security.Key;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.SecureRandom;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjavax.xml.bind.annotation.adapters.HexBinaryAdapter;public classDigestTest{public static voidmain(String[] args){try{
AESEncodeTest();
RSAEncodeTest();
}catch(Exception e){
e.printStackTrace();
}
}/*** AES对称加密
*@throwsException*/
private static void AESEncodeTest() throwsException{
String content= "content";
String key= "key"; //可以将该key存入本地文件,相当于一个秘钥。这个秘钥是不会通过网络传播的。//加密
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, newSecureRandom(key.getBytes()));
SecretKey secretKey=kg.generateKey();byte[] enCodeFormat =secretKey.getEncoded();
SecretKeySpec keySpec= new SecretKeySpec(enCodeFormat, "AES");
Cipher enCipher= Cipher.getInstance("AES");
enCipher.init(Cipher.ENCRYPT_MODE, keySpec);byte[] result =enCipher.doFinal(content.getBytes());
System.out.println("AES加密后:" + newHexBinaryAdapter().marshal(result));//解密//keyGenerator可以重复使用,但是每次使用前都需要调用init方法
kg.init(128, newSecureRandom(key.getBytes()));
SecretKeySpec dekeySpec= new SecretKeySpec(kg.generateKey().getEncoded(),"AES");
Cipher deCipher= Cipher.getInstance("AES");
deCipher.init(Cipher.DECRYPT_MODE, dekeySpec);
System.out.println("AES解密后:" + newString(deCipher.doFinal(result)));
}/*** RSA非对称加密
* 接收方生成的publicKey公布给发送方,发送方使用该公有秘钥加密之后,发送给接收方,然后接收方使用私有秘钥解密
* 如果接收方需要返回消息给发送方,同样也可以接受发送方生成的公有key,使用它加密后发送给发送方*/
private static void RSAEncodeTest() throwsException{
String content= "content";
KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, newSecureRandom());
KeyPair keyPair=keyPairGenerator.generateKeyPair();//这儿模拟接收方生成了公、私有key。这些key可以存到文件里,要使用的时候读取出来即可
Key privateKey =keyPair.getPrivate();
Key publicKey=keyPair.getPublic();//这儿模拟发送方已经获取了接收方给的publicKey,并且使用它来加密要发送的数据
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE, publicKey);byte[] result =cipher.doFinal(content.getBytes());
System.out.println("RSA加密后:" + newHexBinaryAdapter().marshal(result));//这儿模拟接收方使用自己生成的私钥进行解密
Cipher deCipher = Cipher.getInstance("RSA");
deCipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] deResult =deCipher.doFinal(result);
System.out.println("RSA解密后:" + newString(deResult));
}
}