簡體   English   中英

我如何只能從該方法中獲取公鑰的值

[英]How can i get only the value of public key from that method

密鑰生成方法

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

但是我的方法顯示為null我如何通過密鑰存儲庫或任何其他方法將公用/專用密鑰存儲在文件中

您應該可以通過運行以下命令來獲取公鑰字符串:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM