Android RSA加密引发InvalidKeySpecException

时间:2018-11-11 03:25:03

标签: android rsa public-key-encryption

我正在尝试使用给定的公钥加密数据。

public static final String public_key = "MIIBCgKCAQEAr/oYAoxIcXnLzVDNN6TPJVjkwOJZnDcSEeoRntqhOvgjiycfswMWZZ5+UClJ4CMgMCVAs71BzAJzPv902Jt763SPkAO/vh6CwfLq2S3YcqDoRQJYZuSKQHW40R6sN7eFvQdxYhJnF45ketCdLdPFuF5o/ieChwLcCEDKzkWD7xio2TQlZ8jfzB4jNGr6bmW/aqF5ihe0pbhtfvlyM+jNF2vWeB1SCJ4v5zHLNKKYNy4cMsmIGHKB+0BaGVz87eYp65FFc2K9LawBBbWtVCxykYBzEnXRuU+0YzcTi4LThXg1cUsf++LK9qL/G7PZdN6HMGP7DYzgstFLfp8VRpKhqQIDAQAB";

String encryptData(String txt)
{
    String encoded = null;
    try {
        PublicKey key = KeyFactory.getInstance("RSA").generatePublic(
                new X509EncodedKeySpec(Base64.decode(public_key, Base64.DEFAULT)));

        Cipher cph = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cph.init(Cipher.ENCRYPT_MODE, key);
        encoded = Base64.encodeToString(cph.doFinal(txt.getBytes()),
                Base64.DEFAULT);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return encoded;
}

并得到错误

W/System.err: java.security.spec.InvalidKeySpecException: 
java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
    at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:143)
    at com.android.org.conscrypt.OpenSSLRSAKeyFactory.engineGeneratePublic(OpenSSLRSAKeyFactory.java:47)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:172)

我在Python3中使用了相同的公钥,并带有'BEGIN PUBLIC KEY ... END PUBLIC KEY'页眉/页脚,并且效果很好:

public_key = """-----BEGIN PUBLIC KEY-----
MIIBCgKCAQEAr/oYAoxIcXnLzVDNN6TPJVjkwOJZnDcSEeoRntqhOvgjiycfswMWZZ5+UClJ4CMgMCVAs71BzAJzPv902Jt763SPkAO/vh6CwfLq2S3YcqDoRQJYZuSKQHW40R6sN7eFvQdxYhJnF45ketCdLdPFuF5o/ieChwLcCEDKzkWD7xio2TQlZ8jfzB4jNGr6bmW/aqF5ihe0pbhtfvlyM+jNF2vWeB1SCJ4v5zHLNKKYNy4cMsmIGHKB+0BaGVz87eYp65FFc2K9LawBBbWtVCxykYBzEnXRuU+0YzcTi4LThXg1cUsf++LK9qL/G7PZdN6HMGP7DYzgstFLfp8VRpKhqQIDAQAB
-----END PUBLIC KEY-----
"""

def encode(msg):
    rsa_key = RSA.importKey(public_key)
    pks1_v1_5 = PKCS1_v1_5.new(rsa_key)
    encrypted = pks1_v1_5.encrypt(msg.encode('utf-8'))
    encrypted = base64.b64encode(encrypted)
    return encrypted

有人可以帮我吗?

---编辑---

我对Python代码进行了一些调试:进入“ RSA.importKey(public_key)”,我看到它将密钥识别为PEM编码的密钥,删除了页眉/页脚并将其转换为二进制文件(binascii.a2b_base64)。将该二进制文件传递给RSA._importKeyDER,发现它遵循PKCS#1标准,并且在注释中,“ DER对象是具有两个元素的RSAPublicKey SEQUENCE”。

1 个答案:

答案 0 :(得分:0)

由于公钥太长,您是从openssl生成公钥吗?

例如,我从openssl生成并替换了您的公钥,一切正常:

openssl genrsa -out key.pem 1024

openssl rsa -in key.pem -pubout > key.pub

并将key.pub字符串粘贴到您的代码中。