0
密鑰生成方法如何從該方法
public static String generateKeys(String keyAlgorithm, int numBits) {
try {
// Get the public/private key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm);
keyGen.initialize(numBits);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
System.out.println("\n" + "Generating key/value pair using " + privateKey.getAlgorithm() + " algorithm");
// Get the bytes of the public and private keys
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
// Get the formats of the encoded bytes
String formatPrivate = privateKey.getFormat(); // PKCS#8
String formatPublic = publicKey.getFormat(); // X.509
String pv=String.valueOf(privateKeyBytes);
System.out.println("Private Key : " + Base64.encode(pv));
String pb=String.valueOf(publicKeyBytes);
System.out.println("Public Key : " + Base64.encode(pb));
// return pb;
// System.out.println("Private Key : " + Base64.encode(String.valueOf(privateKeyBytes)));
// System.out.println("Public Key : " + Base64.encode(String.valueOf(publicKeyBytes)));
// The bytes can be converted back to public and private key objects
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);
// The original and new keys are the same
// System.out.println(" Are both private keys equal? " + privateKey.equals(privateKey2));
// System.out.println(" Are both public keys equal? " + publicKey.equals(publicKey2));
} catch (InvalidKeySpecException specException) {
System.out.println("Exception");
System.out.println("Invalid Key Spec Exception");
} catch (NoSuchAlgorithmException e) {
System.out.println("Exception");
System.out.println("No such algorithm: " + keyAlgorithm);
}
return null;
}
}
這裏獲得公共密鑰的唯一的價值就是我的密鑰生成代碼 我想從上面的方法獲得公共密鑰的唯一的價值,並將其發送使用序列化到服務器。
String pb=String.valueOf(publicKeyBytes);
System.out.println("Public Key : " + Base64.encode(pb));
但我的方法顯示空 我如何可以存儲通過密鑰存儲庫或任何其他方法在文件中的公鑰/私鑰
你必須對你的標籤更加具體。這是密碼學嗎? – user3437460
是的密碼學 –
請更具體。這是關於如何將其放入文件?那麼純粹的IO問題呢?還是有更多的呢? – loonytune