/**
* 私钥加密的对称算法
*
* @author yajun.wuyj
*/
public class PrivateExample {
public static void main(String[] args) throws Exception {
String text = "世界平衡";
byte[] plainText = text.getBytes("UTF8");
//通过KeyGenerator形成一个key
System.out.println("\nStart generate AES key");
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
Key key = keyGen.generateKey();
System.out.println("Finish generating DES key");
//获得一个私鈅加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
System.out.println("\n" + cipher.getProvider().getInfo());
//使用私鈅加密
System.out.println("\nStart encryption:");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(plainText);
System.out.println("Finish encryption:");
System.out.println(new String(cipherText, "UTF8"));
System.out.println("\nStart decryption:");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println("Finish decryption:");
System.out.println(new String(newPlainText, "UTF8"));
}
}
其中KeyGenerator是专门生成密钥的类。区别于KeyPairGenerator生成的是密钥对。
通过他的getInstance可以获取如下的算法需要的Key。
KeyGenerator
The following algorithm names can be specified when requesting an instance of
KeyGenerator
:
- AES
- ARCFOUR/RC4
- Blowfish
- DES
- DESede
- HmacMD5
- HmacSHA1
- HmacSHA256
- HmacSHA384
- HmacSHA512
- RC2
Cipher.getInstance() 参数可以用一下形式的参数
- "algorithm/mode/padding"
- "algorithm"
mode 模式详见:http://www.cnblogs.com/happyhippy/archive/2006/12/23/601353.html
或者官方一点的:http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
padding 填充模式详见:http://www.cnblogs.com/midea0978/articles/1437257.html
具体所有已经可以用的algorithm详见官方网站:
http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html