只有在 Android 上生成的 RSA 在 Android(5.0+ 设备)下正常工作

Only RSA, generated on Android is working properly under Android (5.0+ devices)

我尝试过使用 RSA。我想检查一下,如果一切正确,所以我使用了加密和解密(仅用于测试)。

看来,只有在android下生成的私钥才能正常工作。

我收到以下关于通过 openssl 生成的 RSA 密钥的错误:

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

对于 public 密钥,所有这些都适用于 androidgenerated 和 opensslgenerated 密钥。

final String RSA_ENCODED_PRIVATE_KEY_ANDROID_GENERATED = "" +
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQD8z7AfzAPlOrKUEOH0fewwLHUq" +
"F+kEhETFTYr+5p0IanXKBZPI+hbvk5zKaZkX6FhyiIdwCmyELsQk2L43xkW6YXzg9bL4xSx06VcA" +
"iWDk4onU3K9pVC51Tq1Z+ygg3zvSSoRaUxW3aNHDygx8oIIJpuOQ7x+2TF8sFq1GIy2YdH/Eih02" +
"s2/w3ExykxBn+5rWgj0ZpoWO34umRfQooYeThbJx94v2ap7lOOPPZFiKvH7mUDbOJfb3xcGPynJE" +
"45oDNaew/yOeAjCS/ISHJcZjF8ip7/YKsMRQXCQxzCyUSSEH9ifj90K46H2vx46E7JHBMQk0IuyL" +
"jqL8V3dYhmibAgMBAAECggEAJ9wjG9BR6OmJUHkc9yyHecz4qCte7Pxhz237dVcs+S+35KNeerib" +
"tyhh9zQRFEjo8R3/pLWwCGNLP7gAvdCAG/PU+a8jib+k08YalpYSdeQV8T7eVVAVhx9hi6di21P3" +
"HZ/sIEWrTeCz+he4QkoYVqc+iBJ7wIVoGA53QXC4dqnPZmPcQgaNOAgfz+FTB6ybPduZhL21Qgtq" +
"1IlJ+N5j8mykILj5J1FqCDq5PJA4BwL7f/QK7xRZ8BJGE/6LCmNjXym6C/Dc+uTpIkFiDE2LfgDG" +
"EWVoSnr5kRdt0ucCGPLyCjQ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J6Q6UneluogwqxQG" +
"q+j4FuM4spMusfXMwTNsLKvr/QoOlIYQVR1VBj2pYLtVKlZL0TDHCJcjCv6jpP2S" +
"fclz9xsv0XZIQvwKpwZtf2IJOeSS2rnR0jk8sC8Gmu6CP5j/hHWOBupL5Nr/muoU" +
"W2gBHcvzvgIhr62DVaZPK1hBAoGBAOqsq3by66UCYvIdJXEF3W24Q3GRXXuXUpmA" +
"fvf/T+1AqQVwBRpQoJBaooPQCCAY2Wkt7j/DuKOYkLXf9RyYcWRHcx7pIH14dXoK" +
"3rocOc05dRh/uE4CN0xxPccr5N/OveBR5dV4eYcP1dgOh4frZyXB+6vXxS+++krJ" +
"yn3Cu375AoGASxHCB0gdfYRyWQEl0WoL1eyohdAJf08kVBZtAQ2jLeqY0ZEdUpzG" +
"+99qyw2IysGMwmjCxribLwbUm2cg74lZnX0NQH4HfQ5Pp4c0RUyJARrVzPhyQ1lu" +
"vgPZpCebTX9/118crlHQlTiGD4M258ghR8msm/+p4Efl8NvEcQ35y04=";

byte[] keyBytes = Base64.decode(RSA_ENCODED_PRIVATE_KEY_ANDROID_GENERATED, Base64.DEFAULT);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(spec);//working    

byte[] keyBytesOpenSSL = Base64.decode(RSA_ENCODED_PRIVATE_KEY_OPENSSL_GENERATED, Base64.DEFAULT);
PKCS8EncodedKeySpec specOpenSSL = new PKCS8EncodedKeySpec(keyBytesOpenSSL);
KeyFactory keyFactoryOpenSSL = KeyFactory.getInstance("RSA");
PrivateKey keyOpenSSL = keyFactoryOpenSSL.generatePrivate(specOpenSSLenter code here);//java.security.spec.InvalidKeySpecException

OPENSSL 版本的结构与 ANDROID 不同。

在在线 ASN.1 解码器中查看两种数据结构:

RSA_ENCODED_PRIVATE_KEY_ANDROID_GENERATED

RSA_ENCODED_PRIVATE_KEY_OPENSSL_GENERATED

因此我假设 OPENSSL 版本不是有效的 PKCS#8 structure,只是一个包含 PrivateKey 结构的子集。

可能是您使用 OpenSSL 执行了错误的命令,如果我阅读正确的文档,它会默认创建一个 PKCS#1 结构。如果你想要 PKCS#8 结构,你必须稍后使用 openssl pkcs8 .. 命令转换它。