从Bouncy Castle中的文本创建RSA公钥时遇到问题

时间:2019-04-09 03:00:27

标签: java encryption jwt rsa

从公共密钥文本创建公共密钥时遇到问题。我从此链接Creating RSA Public Key From String找到了解决方案。他们提到Bouncy Castle(轻量级API)是一个库,用于解决将公钥字符串转换为RSA公钥时的 InvalidKeySpecException 错误。但是这种解决方案因我的情况而失败。程序在这里抛出异常

线程“ main”中的异常java.lang.IllegalArgumentException:错误的序列大小:9

Creating RSA Public Key From String

   String publicKeyB64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3AQKDhhtcM5A1a8R9/VX" +
            "mrocKGaQlat2/MRFy/Y1fTabYyKkfgaRXyrHiRn+imq3ljEgx/vLRTTPtLt8H79a" +
            "iMU6WJkQwG504NCnDRVB9DZBoAYDtBkjtje7I2Xs3tzvlNwM0bcCmmj/6QE9rHEv" +
            "xhvvXO8M332hINORLNiCF6NvYHrIVSa8EU4F0bnlWpoNi0YhP45uyOOuPpVmsaxp" +
            "MWOycf3nTICKK5BDylnVO7kMcL1utJxOOb1fsotaLuge4fF84DG4cPpLZko3ksB/" +
            "voOLTDv5QRsn++8qRciK4sptlnOs8g2TrXjE/rZlP9QmpUV4a3iQ1WmsqWQVizmw" +
            "PwIDAQAB";

    byte[] decoded = Base64.getDecoder().decode(publicKeyB64);
    org.bouncycastle.asn1.pkcs.RSAPublicKey pkcs1PublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(decoded);
    BigInteger modulus = pkcs1PublicKey.getModulus();
    BigInteger publicExponent = pkcs1PublicKey.getPublicExponent();
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey generatedPublic = kf.generatePublic(keySpec);
    System.out.printf("Modulus: %X%n", modulus);
    System.out.printf("Public exponent: %d ... 17? Why?%n", publicExponent); // 17? OK.
    System.out.printf("See, Java class result: %s, is RSAPublicKey: %b%n", generatedPublic.getClass().getName(), generatedPublic instanceof RSAPublicKey);

所以我真的很希望能得到解决的建议。

2 个答案:

答案 0 :(得分:1)

您现在编辑的数据是公钥,但不是PKCS1格式;它以更常见(并且通常更有用)的X.509 SubjectPublicKeyInfo格式。 the Q you linked中对此差异进行了说明。尽管BouncyCastle支持这种格式,但Java加密(JCA)也使用(技术上不精确的)名称X509EncodedKeySpec直接支持该格式,因此,这样做更加简单:

byte[] decoded = Base64.getDecoder().decode(publicKeyB64);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey generatedPublic = kf.generatePublic(new X509EncodedKeySpec(decoded));

答案 1 :(得分:0)

如果您的公钥正确,那么您应该能够在命令行上读取它,以便解决问题。尝试使用以下命令:

$ openssl rsa -inform PEM -pubin -in pub.key -text -noout
$ openssl pkey -inform PEM -pubin -in pub.key -text -noout

用您的公共密钥文件替换“ pub.key”。