PEM到Android中的PublicKey [英] PEM to PublicKey in Android

查看:919
本文介绍了PEM到Android中的PublicKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多类似的问题,但没有什么对我有用。我只是尝试将我从服务器检索到的PEM格式的RSA公钥转换为Android中的 PublicKey 。任何人都可以指出我正确的方向吗?

I've seen a number of similar questions, but nothing has quite worked for me. I am simply trying to convert an RSA public key that's in PEM format that I've retrieved from a server into a PublicKeyin Android. Can anyone point me in the right direction?

编辑:
我已成功使用以下代码将PEM转换为PublicKey,但在编码时消息,我得到意外的输出...

I've successfully used the following code to convert the PEM into a PublicKey, but upon encoding a message, I get unexpected output...

 public PublicKey getFromString(String keystr) throws Exception
    {
        // Remove the first and last lines

        String pubKeyPEM = keystr.replace("-----BEGIN PUBLIC KEY-----\n", "");
        pubKeyPEM = pubKeyPEM.replace("-----END PUBLIC KEY-----", "");

        // Base64 decode the data

        byte [] encoded = Base64.decode(pubKeyPEM);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pubkey = kf.generatePublic(keySpec);

        return pubkey;
    }

    public String RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {

        if (pubKey!=null) {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            encryptedBytes = cipher.doFinal(plain.getBytes());
            Log.d("BYTES", new String(encryptedBytes));
            return Hex.encodeHexString(encryptedBytes);
        }
        else
            return null;
    }

输出如下:

b6813f8791d67c0fa82890d005c8ff554b57143b752b34784ad271ec01bfaa9a6a31e7ae08444baef1585a6f78f3f848eecb1706bf7b2868fccefc9d728c30480f3aabc9ac5c3a9b4b3c74c2f7d6f0da235234953ea24b644112e04a2ec619f6bf95306ef30563c4608ec4b53ed7c15736d5f79c7fa1e35f2444beb366ae4c71

当我期望更接近于:

JfoSJGo1qELUbpzH8d4QXtafup+J2F9wLxHCop00BQ4YS0cRdRCKDfHpFPZQYjNeyQj00HwHbz+vj8haTPbpdqT94AHAl+VZ+TPAiUw1U5EXLLyy4tzbmfVI7CwvMm26lwB4REzYUZdedha1caxMEfxQ5duB+x4ol9eRZM/savg=

我缺少一些格式或文件类型吗?

Is there some formatting or file type that I'm missing?

推荐答案

回答我自己的问题......第一个输出是十六进制,第二个输出是基数64.只需将return语句更改为返回new String(Base64.encode(encryptedBytes) ));
,你会很好!

To answer my own question...The first output is in hex and the second output is in base 64. Just change the return statement to return new String(Base64.encode(encryptedBytes)); and you'll be good!

这篇关于PEM到Android中的PublicKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆