随机密钥生成
// 随机生成密钥
protected static Map<String, Object> initKey( ) throws Exception{
//实例化密钥对生成器
KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
// 初始化密钥对生成器
keyPairGen.initialize(KEY_SIZE);
// 生成密钥对
KeyPair keyPair=keyPairGen.generateKeyPair();
//公钥
RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
//私钥
RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
// 得到公钥字符串
String publicKeyString = Base64.encode(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = Base64.encode(privateKey.getEncoded());
System.out.println("PUBLIC_KEY:"+publicKeyString);
System.out.println("PRIVATE_KEY:"+privateKeyString);
// 封装密钥
Map<String, Object> keyMap=new HashMap<String,Object>(2);
keyMap.put(PUBLIC_KEY, publicKeyString);
keyMap.put(PRIVATE_KEY, privateKeyString);
return keyMap;
}
// 根据信息生成 固定密钥
因为在初始化keyPairGen时候,需要传入一个随机数,如果不传底层应该默认了随机,如果有第二个参数应该根据这个参数生成密钥!只是猜测,但是如果第二个参数固定,密钥生成也是固定!亲测
// 根据固定值生成 固定密钥对儿
protected static Map<String, Object> initKey2( ) throws Exception{
/** RSA算法要求有一个可信任的随机数源 */
String str_deta=new String("12345678");
SecureRandom secureRandom=new SecureRandom(str_deta.getBytes());
System.out.println("secureRandom"+secureRandom.hashCode());
//实例化密钥对生成器
KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
// 初始化密钥对生成器
//keyPairGen.initialize(KEY_SIZE);
keyPairGen.initialize(KEY_SIZE, secureRandom);
// 生成密钥对
KeyPair keyPair=keyPairGen.generateKeyPair();
//公钥
RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
//私钥
RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
// 得到公钥字符串
String publicKeyString = Base64.encode(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = Base64.encode(privateKey.getEncoded());
System.out.println("PUBLIC_KEY:"+publicKeyString);
System.out.println("PRIVATE_KEY:"+privateKeyString);
// 封装密钥
Map<String, Object> keyMap=new HashMap<String,Object>(2);
keyMap.put(PUBLIC_KEY, publicKeyString);
keyMap.put(PRIVATE_KEY, privateKeyString);
return keyMap;
}