最近闲来无事..稍稍的研究了下java安全.说到安全 加密->解密 数字摘要MD5/SHA算法 数字签名,数字证书等..
[b]密钥加密[/b]
如果不初始化的会抛这么个异常
[b]密钥加密[/b]
package org.deepsap.security;
import java.security.*;
import javax.crypto.*;
/***
*
* @author WeiJ
*
*/
public class PrivateKeyTest {
public static void main(String[] args) throws Exception {
byte[] plainText = "这只是一个奇迹".getBytes("UTF8");
// 得到DES私钥
System.out.println("\n开始生成AES私钥");
long beginTime = System.currentTimeMillis();
Key key = KeyGenerator.getInstance("AES").generateKey();
System.out.println("生成DES私钥已完成,耗时共"
+ (System.currentTimeMillis() - beginTime) + "ms");
// 得到AES cipher 对象,并打印出算法的提供者
Cipher cipher = Cipher.getInstance("AES");
System.out.println("\n" + cipher.getProvider().getInfo());
// 使用密钥对文本进行加密
System.out.println("\n开始加密");
// 加密之前需先初始化Cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(plainText);
System.out.println("\n完成加密");
System.out.println("加密后的:" + new String(result, "UTF8"));
// 使用同一把密钥对密文进行解密
System.out.println("\n开始解密");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] newResult = cipher.doFinal(result);
System.out.println("完成解密: ");
System.out.println(new String(newResult, "UTF8"));
}
}
如果不初始化的会抛这么个异常
Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized
at javax.crypto.Cipher.c(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at org.deepsap.security.PrivateKeyTest.main(PrivateKeyTest.java:31)