从Base64编码的String生成PublicKey

时间:2014-03-13 06:45:00

标签: android

我需要使用PublicKey来加密会话密钥,但我将公钥作为Base64编码的字符串,所以我尝试将其转换为:

KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
byte[] keyBytes = _publicKey.getBytes();
byte[] publicKeyBytes = Base64.decode(keyBytes, Base64.DEFAULT);

X509EncodedKeySpec publicKeySpecs = new X509EncodedKeySpec(publicKeyBytes);
Log.v("", "X509  KS" + publicKeySpecs);
publicKey = kf.generatePublic(publicKeySpecs);

但是我将公钥作为空值获取并获得异常:

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag

如果有人知道如何操作或有工作代码,请帮助我。

先谢谢

2 个答案:

答案 0 :(得分:2)

大家好我从Public Key编码的字符串生成了Base64

在想了几天之后,这段代码对我有用了。

String _publicKey= base64encoded_publickey;


    // InputStream fileInputStream = null;
    try {
        // Receiving side

        byte[] decodedBytes = Base64.decode(_publicKey, Base64.DEFAULT);

        fileInputStream = new ByteArrayInputStream(decodedBytes);

        // Print the decoded string

        String decodedString = new String(decodedBytes);


        CertificateFactory certFactory = CertificateFactory
                .getInstance(CERTIFICATE_TYPE);
        // certFactory.
        X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(fileInputStream);
        publicKey = cert.getPublicKey();
        Log.d("TAG", "Public key of the certificate:" + publicKey);


    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not intialize encryption module",
                e);
    } finally {
        if (keyStream != null) {
            try {
                keyStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

希望它会对你有所帮助......谢谢......

答案 1 :(得分:0)

好吧,上次它对我有用(我使用了bouncyCastle库..),如果它不适合你的需要你可能需要修改它。

KeyPairGenerator keyGen = null;
KeyPair kp = null;

keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");

ECGenParameterSpec ecSpec = new ECGenParameterSpec("brainpoolp160r1");
keyGen.initialize(ecSpec, new SecureRandom());

kp = keyGen.generateKeyPair();

修改: (哎呀我的坏,那是初代......) 那时我把它们存储为一个...... 我需要先将Base64字符串转换回byte数组,然后将它们拆分为第1部分和第2部分。

private void splitKeyPair (byte[] thekeypair, byte[] part1, byte[] part2)
{
    System.arraycopy(thekeypair, 0, part1, 0, 68);
    System.arraycopy(thekeypair, 68, part2, 0, 115);
}

byte[] part1 = new byte[68];
byte[] part2 = new byte[115];
splitKeyPair(inputBuffer, part1, part2);

fact = KeyFactory.getInstance("ECDSA", "BC");
kp = new KeyPair(fact.generatePublic(new X509EncodedKeySpec(part1)),
                    fact.generatePrivate(new PKCS8EncodedKeySpec(part2)));

希望它有帮助.. *注意:尺寸可能会有所不同,具体取决于规格..