tags:

views:

113

answers:

2

I am developing an Android Application and I need to generate some RSA private and public keys to use for secure communication with web services. To do this I need to have the public key in a .NET compatible form. Like:

<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>

So far I managed to to this:

  keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(1024);
  keypair = keyGen.genKeyPair();
  privateKey = keypair.getPrivate();
  publicKey = keypair.getPublic();

  // Get the bytes of the public and private keys
  byte[] privateKeyBytes = privateKey.getEncoded();
  byte[] publicKeyBytes = publicKey.getEncoded();

I've got no clue how to continue. Could you please provide some help ?

A: 

You don't show the type publicKey. If is not already, you should cast to an RSAPublicKey, then use the getPublicExponent() and getModulus() methods to extract the BigInteger. Then simply use standard Java IO, e.q. PrintStream.println() or printf() to generate the XML components.

GregS
To serialize this into `<RSAKeyValue>` (which is presumably comes from the XML Digital Signature format), you also need to base64-encode the values obtained from `getPublicExponent()` and `getModulus()`, not just use `toString()` directly.
Bruno
@Bruno: thanks, I was not familiar with the spec and just guessed about what was needed for {0} and {1}.
GregS
A: 

For anybody else interested, a very good tut[link text][1]orial can be found in here http://www.codeproject.com/KB/security/porting_java_public_key.aspx?msg=3407475

If you need Base64 encoding/decoding, because it's not included in Android (at least in API 4) you could use the class from here: iharder.sourceforge.net/current/java/base64/

Alin