无法将私钥转换为字符串

问题描述 投票:0回答:1

我想将私钥转换为字符串,以便用户可以将其存储在硬状态。

我尝试使用 Base64 转换私钥,但它给我错误,指出 privateKey.getEncoded() 为 null

所以我在 Base64 之前尝试过,但再次得到 null 。

public String newKey() throws
            NoSuchAlgorithmException,
            NoSuchProviderException,
            InvalidAlgorithmParameterException, KeyStoreException, CertificateEncodingException, UnrecoverableEntryException {

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, KEYSTORE);
        KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec
                .Builder(alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
                .setEncryptionPaddings(PADDING)
                .build();

        keyPairGenerator.initialize(keyGenParameterSpec);
        PrivateKey key = keyPairGenerator.generateKeyPair().getPrivate();

        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,null);
        String a = privateKeyEntryToString(entry,key);
        //  java.util.Base64.getDecoder().decode(entry)
        //  Log.d("tag",entry);


        Log.d("tag", "done in new Key returning keypublic");
        return a;
       // return keyPairGenerator.generateKeyPair().getPublic();

    }
    private String privateKeyEntryToString(KeyStore.PrivateKeyEntry privateKeyEntry,PrivateKey key) throws CertificateEncodingException {

 Certificate certificate = privateKeyEntry.getCertificate();
        if (key.getEncoded().length == 0){ // but here we get exception that it is null.
            return "its empty";
        }
        
        

        // Convert PrivateKey and Certificate to String
        String privateKeyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
        String certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT);

        // Combine both strings with a separator for later use
        return privateKeyString + "-----BEGIN CERTIFICATE-----\n" + certificateString;

堆栈跟踪:

FATAL EXCEPTION: main
Process: com.leo.nopasswordforyou, PID: 9525
java.lang.NullPointerException: Attempt to get length of null array
android encryption rsa private-key android-keystore
1个回答
0
投票

问题是我从 keyPairGenerator.generateKeyPair() 获取私钥,这是否意味着生成 keyPair 后,它将它们存储在 KeyPair 中,当提示接收时,它会转发密钥库的 key 。例如:

keyPairGenerator.generateKeyPair().getPrivate();

我认为这就是误解所在。密钥是在 Android 密钥存储中生成的,而不是导入到其中。 Android 密钥存储确实保护私钥的值。 如果您想在软件中创建密钥,那么您可以简单地尝试完全删除命名错误的 KEYSTORE 参数;默认情况下,不会使用 Android

provider

。是的,这是一个有点奇怪的 API,你可能不能只是将其设置为

null
并保持兼容;如果这样做,您可能还需要从任何 catch 子句中删除 NoSuchProviderException
    

© www.soinside.com 2019 - 2024. All rights reserved.