将公钥转换为字符串

时间:2017-01-13 14:20:07

标签: android keystore public-key-encryption android-keystore

在我的开发步骤中,我需要使用一个API,它需要我发送一个RSA公钥,如:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAsFxynduUThmOU9j7Qg7C/XOKVccJ26AlL/SdEDA1YcFLfG4XcmLm
2rYAq4ia52tIJRuaiDGxaG3EKB38J35ycUe0pB48x+y+rMLDtn/p3PxyfOmkZ+VT
vKN025eNG9MisO+r6dQY8UaODtvRBzov2oB7+sQUD0i2zn7F5BmO86wFxibSk4OG
ssgNyrg6G/H7X/AssgWWtUDV+r4hHRu1aDYJHoNeYTF/nMZl3g9cxuASBOfDemNS
iZPCqiGKuZ3X3tdUBkz/XlkeC+X/tJT9TBEnY2SS4FllHQcMhYaTiKf1ScG3JLbd
ekJCK2fnzXAp/3+Wp0GZD12de/7XLaPMhwIDAQAB
-----END RSA PUBLIC KEY-----

为此,我使用Android的Keystore API,我这样做:

KeyStore keyStore = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
        keyStore.load(null);

        String alias = SecurityConstants.KEYSTORE_KEY_ALIAS;

        // Create the keys if necessary
        if (!keyStore.containsAlias(alias)) {

            Calendar notBefore = Calendar.getInstance();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.YEAR, 1);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(alias)
                    .setKeyType(KeyProperties.KEY_ALGORITHM_RSA)
                    .setKeySize(2048)
                    .setSubject(new X500Principal("CN=test"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(notBefore.getTime())
                    .setEndDate(notAfter.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA, SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
            generator.initialize(spec);

            KeyPair keyPair = generator.generateKeyPair();
        }

现在问题是,我必须将公钥作为一个字符串,我不确定这样做的正确方法,但我这样做了:

public static PublicKey getPublicKey() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableEntryException {
    KeyStore keyStore = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(SecurityConstants.KEYSTORE_KEY_ALIAS, null);
    return privateKeyEntry.getCertificate().getPublicKey();
}

public static String getPublicKeyAsString() {
    try {
        return "-----BEGIN RSA PUBLIC KEY-----\n" + Base64.encodeToString(getPublicKey().getEncoded(), Base64.DEFAULT) +
                "-----END RSA PUBLIC KEY-----";
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnrecoverableEntryException e) {
        e.printStackTrace();
    }
    return null;
}

我设法得到一个字符串,但我不确定这是否可行,可能与它应该存储在密钥库中的密钥不同,我没有看到谷歌主张这样做。有人有这种经历吗?

0 个答案:

没有答案