gpt4 book ai didi

java - 为什么我的 Java RSA 加密会出现算术异常?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:30 24 4
gpt4 key购买 nike

在 .NET 中,我生成了以下公钥文件:

<RSAKeyValue>
<Modulus>xTSiS4+I/x9awUXcF66Ffw7tracsQfGCn6g6k/hGkLquHYMFTCYk4mOB5NwLwqczwvl8HkQfDShGcvrm47XHKUzA8iadWdA5n4toBECzRxiCWCHm1KEg59LUD3fxTG5ogGiNxDj9wSguCIzFdUxBYq5ot2J4iLgGu0qShml5vwk=</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>

.NET 很乐意使用它的常规方法进行加密。

我正在尝试使用此 key 在 Java 中对字符串进行编码。当我尝试加密字符串时遇到算术异常。

下面是我用来加密的代码:

byte[] modulusBytes = Base64.decode(this.getString(R.string.public_key_modulus));
byte[] exponentBytes = Base64.decode(this.getString(R.string.public_key_exponent));
BigInteger modulus = new BigInteger( modulusBytes );
BigInteger exponent = new BigInteger( exponentBytes);

RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);

byte[] cipherData = cipher.doFinal( new String("big kitty dancing").getBytes() );

失败的是代码块中的最后一行。

我看了很多例子,这是我能想到的最好的例子。如果不是很明显,R.string.public_key_modulus 是 Modulus 元素中文本的复制/粘贴,同样适用于指数。

我做错了什么?

最佳答案

试试这个:

BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);

否则你最终会得到一个负模数。 BigInteger(byte[]) 构造函数采用signed 大端表示法。 BigInteger(int, byte[]) 构造函数使用提供的符号位(此处“1”表示“正”)。

此外,请注意 String.getBytes(),它使用平台“默认字符集”,这取决于运行应用程序的机器的配置。如果您想要可重现的结果,最好指定一个明确的字符集(例如 "UTF-8")。

关于java - 为什么我的 Java RSA 加密会出现算术异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2691579/

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