gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:19 25 4
gpt4 key购买 nike

我想在无法假定 HTTPS 可用的情况下确保 Android 应用程序和 C# ASP.NET 服务器之间的消息隐私。

我想使用 RSA 加密从 Android 设备首次连接服务器时传输的对称 key 。

RSA key 对已经在服务器上生成,私钥保存在服务器上。 key 对是在 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)嵌入公钥是行不通的。代码在 rsaCipher.doFinal() 方法调用上抛出 org.bouncycaSTLe.crypto.DataLengthException: input too large for RSA cipher。

// 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 中生成公钥成功加密了 key 。我使用了这段代码:

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

那么,我做错了什么?

最佳答案

尝试使用 new BigInteger(1, modulus)。 BigIntegers 是有符号的,并且由于模数从第一位设置为 1 开始,因此它将始终被解释为负数。

关于c# - 如何在 Android 中使用 C# 生成的 RSA 公钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com