由于缺少ASN1支持,因此解析PKCS1(在Android上仅开箱即用的PKCS8格式)键是一项繁琐的任务,但如果包含Spongy castle jar以读取DER Integers,则可以解决。
String privKeyPEM = key.replace("-----BEGIN RSA PRIVATE KEY-----n", "") .replace("-----END RSA PRIVATE KEY-----", "");// base64 depre the databyte[] enpredPrivateKey = base64.depre(privKeyPEM, base64.DEFAULT);try { ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence .fromByteArray(enpredPrivateKey); Enumeration<?> e = primitive.getObjects(); BigInteger v = ((DERInteger) e.nextElement()).getValue(); int version = v.intValue(); if (version != 0 && version != 1) { throw new IllegalArgumentException("wrong version for RSA private key"); } BigInteger modulus = ((DERInteger) e.nextElement()).getValue(); BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue(); BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue(); BigInteger prime1 = ((DERInteger) e.nextElement()).getValue(); BigInteger prime2 = ((DERInteger) e.nextElement()).getValue(); BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue(); BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue(); BigInteger coefficient = ((DERInteger) e.nextElement()).getValue(); RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pk = kf.generatePrivate(spec);} catch (IOException e2) { throw new IllegalStateException();} catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e);} catch (InvalidKeySpecException e) { throw new IllegalStateException(e);}


