public String getPrivateKeyAsXml(PublicKey publicKey, PrivateKey privateKey) throws Exception
{
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKeySpec ksPublic = kf.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec ksPrivate = kf.getKeySpec(privateKey, RSAPrivateKeySpec.class);
BigInteger n = ksPublic.getModulus();
BigInteger e = ksPublic.getPublicExponent();
BigInteger d = ksPrivate.getPrivateExponent();
BigInteger p = findFactor(e, d, n);
BigInteger q = n.divide(p);
if (p.compareTo(q) > 1) {
BigInteger t = p;
p = q;
q = t;
}
BigInteger dp = d.mod(p.subtract(BigInteger.ONE));
BigInteger dq = d.mod(q.subtract(BigInteger.ONE));
BigInteger inverseQ = q.modInverse(p);
String publicKeyAsXML = "<RSAKeyValue>" +
"<Modulus>" + convertToString(n) + "</Modulus>" +
"<Exponent>" + convertToString(e) + "</Exponent>" +
"<P>" + convertToString(p) + "</P>" +
"<Q>" + convertToString(q) + "</Q>" +
"<DP>" + convertToString(dp) + "</DP>" +
"<DQ>" + convertToString(dq) + "</DQ>" +
"<InverseQ>" + convertToString(inverseQ) + "</InverseQ>" +
"<D>" + convertToString(d) + "</D>" +
"</RSAKeyValue>";
Log.d(TAG, "getPrivateKeyAsXml: " + publicKeyAsXML);
return publicKeyAsXML;
}
private String convertToString(BigInteger n) {
return Base64.encodeToString(n.toByteArray(), Base64.NO_WRAP);
}
-r
.