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

时间:2015-09-02 07:41:07

标签: 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 如何通过密钥库或任何其他方法将公钥/私钥存储在文件中

1 个答案:

答案 0 :(得分:0)

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

System.out.println(new String(java.util.Base64.getEncoder()。encode(publicKeyBytes)));