如何从该方法中获取公钥的值?

  • 本文关键字:公钥 获取 方法 java
  • 更新时间 :
  • 英文 :


密钥生成方法

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;
    }
}

这是我的密钥生成代码我只想从上述方法中获取Public Key的值,并使用序列化将其发送到服务器。

 String pb=String.valueOf(publicKeyBytes);
 System.out.println("Public Key : " + Base64.encode(pb));

但是我的方法显示null如何通过密钥存储库或任何其他方法将公钥/私钥存储在文件中

您应该能够通过运行以下命令获得公钥字符串:

system . out。println(新字符串(java.util.Base64.getEncoder () .encode (publicKeyBytes))),

最新更新