Gravity Gravity - 7 months ago 71
Android Question

Generating a KeyPair and getting modulus and exponent from Public Key in Android

I generated a Public Private Key Pair in Android. Now I need to send my Public Key back to the Server for communicating with RSA Encryption. However, I am communicating with a .NET Server (in C#). Therefore I need to send my Public Key in the following format:

<RSAKeyValue><Modulus>Modulus In Base 64</Modulus><Exponent>Exponent in Base 64</Exponent></RSAKeyValue>

I generate the key Pair with the following code:

public static void generateKey() {

final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair key = keyGen.generateKeyPair();
privateKey = key.getPrivate();
publicKey = key.getPublic();

} catch (NoSuchAlgorithmException e) {

How can I extract the modulus and exponent of the PublicKey I just generated?


There was no native Android method to solve my problem. In order to extract the modulus and exponent of the generated Public Key, I used the following code, which takes an Android Public Key as Input and returns it in the .NET XML Format:

   public static String getPublicKeyAsXml(PublicKey publicKey) throws Exception


        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec ks = kf.getKeySpec(publicKey, RSAPublicKeySpec.class);
        BigInteger modulus = ks.getModulus();
        BigInteger exponent = ks.getPublicExponent();
        byte[] modByte = modulus.toByteArray();
        byte[] expByte = exponent.toByteArray();
        modByte = testBytes(modByte);
        expByte = testBytes(expByte);
        String encodedModulus = Base64.encodeToString(modByte, Base64.NO_WRAP);
        String encodedExponent = Base64.encodeToString(expByte, Base64.NO_WRAP);
        String publicKeyAsXML = "<RSAKeyValue>" +
                "<Modulus>" + encodedModulus + "</Modulus>" +
                "<Exponent>" + encodedExponent + "</Exponent>" +

        return publicKeyAsXML;