如何在Android中使用C#生成的RSA公钥?

时间:2012-08-16 05:57:31

标签: c# android .net encryption rsa

我想确保Android应用和C#ASP.NET服务器之间的邮件隐私,在这种情况下,无法假定HTTPS可用。

我想使用RSA加密在首次与服务器联系时从Android设备传输的对称密钥。

已在服务器上生成RSA密钥对,并且私钥保留在服务器上。 密钥对是在C#中使用:

生成的
// Create a new instance of RSACryptoServiceProvider
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
// Ensure that the key doesn't get persisted
rsa.PersistKeyInCsp = false;
RSAParameters parameters = rsa.ExportParameters(false);
string modulus = Convert.ToBase64String(parameters.Modulus);
string exponent = Convert.ToBase64String(parameters.Exponent);
string xmlKeys = rsa.ToXmlString(true);

尝试通过硬编码嵌入公钥(从Visual Studio复制到Eclipse)不起作用。代码抛出一个org.bouncycastle.crypto.DataLengthException:输入对于rsaCipher.doFinal()方法调用的RSA密码来说太大了。

// Generate a new AES key
byte[] key = null;
try {
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);            
    key = keygen.generateKey().getEncoded();
}
catch (NoSuchAlgorithmException e) {}

// Set up modulus and exponent
String mod = "qgx5606ADkXRxndzurIRa5GDxzDYg5Xajeym7I8BXG1HBSzaaGmX+rjQfZK1h4JtQU+Xaowsc81mgJU8+gwneQa56r1bl6/5jFue4FsdXKfpau5az8rY2SAHKcOeyHAOsT9ZqcNa1x6cL/jl9P3cBtOzMk51Hk/w6VNoQ5JJo/0m/eAJzlhVKr2xbOYFhd0xp3qUgRuK8TN4TsSvfc+R1LOWc8+3H22Zj3vhBxSqSgeXxdxi7ThiGiAl6HUwMf8ph7FHNJvoUQq+QPL6dx77pu6xVFiHv1JOfpbKcOubn0VSPLYKY3QPKCzNMYQ6pxUDqzpGtydHR1xaX5K0FGTraw==";

String ex = "AQAB";
BigInteger modulus = new BigInteger(Base64.decode(mod, Base64.DEFAULT));
BigInteger exponent = new BigInteger(Base64.decode(ex, Base64.DEFAULT));

// Encrypt the AES key
PublicKey pubKey;
byte[] cipherData;
try {
    pubKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpe(modulus, exponent));
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");     
    rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
    // The following line fails with:
    // org.bouncycastle.crypto.DataLengthException
    cipherData = rsaCipher.doFinal(key);     
}
catch (InvalidKeySpecException e) {}
catch (NoSuchAlgorithmException e) {}
catch (InvalidKeyException e) {}
catch (NoSuchPaddingException e) {}
catch (BadPaddingException e) {}
catch (IllegalBlockSizeException e) {}

我怀疑我已经错误地解码了模数字符串,因为在Android中生成公钥会成功加密密钥。我用了这段代码:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");     
kpg.initialize(1024);     
KeyPair kpa = kpg.genKeyPair();     
pubKey = kpa.getPublic();   

那么,我做错了什么?

1 个答案:

答案 0 :(得分:7)

尝试使用new BigInteger(1, modulus)。 BigIntegers是签名的,当模数从第一位设置为1开始时,它将始终被解释为负数。