密钥、公钥的字符串以文件形式保存和读取
项目中常常需要下载对方的公钥来做数字签名验证,公钥一般是不会变得,所以我们也只需要下载一次就可以,然后以文件形式保存;得到的公钥往往是一个字符串,以下代码是对公钥的保存和读取:
1、保存到e:/pubkey.dat文件中
//pubKeyStr公钥字符串
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
new BASE64Decoder().decodeBuffer(pubKeyStr));
// RSA对称加密算法
java.security.KeyFactory keyFactory;
keyFactory = java.security.KeyFactory.getInstance("RSA");
// 取公钥匙对象
PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
FileOutputStream fs_pubkey = new FileOutputStream("e:/pubkey.dat");
fs_pubkey.write(publicKey.getEncoded());
fs_pubkey.close();
2、读取
File file = new File("e:/pubkey.dat");
if (file.exists()) {//文件存在
FileInputStream fsKey = new FileInputStream(file);
BufferedInputStream bfsKey = new BufferedInputStream(fsKey);
byte[] byteKey = new byte[bfsKey.available()];
bfsKey.read(byteKey);
bfsKey.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);}