密钥对的存储和加载
1.存储密钥对
首先使用KeyPairGeneration产生密钥对:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keyPair = keyGen.genKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
将密钥存储为文件的方法:
FileOutputStream fs = new FileOutputStream(fileName);
fs.write(privateKey.getEncoded());
fs.close();
2.加载密钥对
假设公钥文件为public.dat、private.dat
首先读取公钥文件:
//read public key
FileInputStream fsPublicKey = new FileInputStream(publicKeyFile);
BufferedInputStream bfsPublicKey = new BufferedInputStream(fsPublicKey);
byte[] bytePublicKey = new byte[bfsPublicKey.available()];
bfsPublicKey.read(bytePublicKey);
bfsPublicKey.close();
使用KeyFactory产生公钥
//build public key
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(
byteEncodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
主意,私钥的的处理和公钥相同,唯一不同的是私钥的KeySpec不同。私钥应使用PKCS8EncodedKeySpec
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论