gpt4 book ai didi

java - RSA 身份验证问题

转载 作者:行者123 更新时间:2023-11-30 04:36:03 24 4
gpt4 key购买 nike

我正在制作一个系统,我想通过 RSA 验证服务器的身份,但我似乎无法让服务器正确解密客户端的消息。

公钥和私钥位于数组的槽 0 中,mod 位于槽 1 中,因此它们设置正确。

客户端代码

int keyLength = 3072 / 8;//RSA key size
byte[] data = new byte[keyLength];

//Generate some random data. Note that
//Only the fist half of this will be used.
new SecureRandom().nextBytes(data);

int serverKeySize = in.readInt();
if (serverKeySize != keyLength) {//Definitely not the right heard
return false;
}

//Take the server's half of the random data and pass ours
in.readFully(data, keyLength / 2 , keyLength / 2);

//Encrypt the data
BigInteger[] keys = getKeys();
BigInteger original = new BigInteger(data);
BigInteger encrypted = original.modPow(keys[0], keys[1]);
data = encrypted.toByteArray();

out.write(data);

//If the server's hash doesn't match, the server has the wrong key!
in.readFully(data, 0, data.length);

BigInteger decrypted = new BigInteger(data);

return original.equals(decrypted);

服务器端代码

int keyLength = 3072 / 8;//Key length
byte[] data = new byte[keyLength];

//Send the second half of the key
out.write(data, keyLength / 2, keyLength / 2);
in.readFully(data);

BigInteger[] keys = getKeys();
BigInteger encrypted = new BigInteger(data);
BigInteger original = encrypted.modPow(keys[0], keys[1]);
data = original.toByteArray();

out.write(data);

据我所知,实现是正确的,但它似乎没有产生正确的输出。也不,出于各种原因,我不想使用密码。

最佳答案

有一些关键细节没有得到考虑。您想要应用 RSA 的数据必须编码为 BigInteger x,其中 0 <= x < n,其中 n 是您的模数。你没有这样做。事实上,因为您用随机数据填充整个数据数组,所以您无法保证这一点。 PKCS#1 填充算法旨在正确执行此操作,但由于您正在滚动自己的算法,因此必须在代码中修复此问题。另外,请仔细检查 BigInteger(byte[]) 构造函数和 BigInteger.toByteArray() 如何解码/编码整数。许多人天真地期望简单的基数 256 编码,而忘记了 BigInteger 也必须容纳负整数。它通过使用 ASN.1 DER 整数规则来实现这一点。如果正整数的高位字节 >= 128,则添加前导零字节。

关于java - RSA 身份验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13506791/

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