Java RSA身份验证问题

Java RSA身份验证问题,java,authentication,rsa,Java,Authentication,Rsa,我正在制作一个系统,我想通过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

我正在制作一个系统,我想通过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);
服务器端代码

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);

AFAIK认为实现是正确的,但是它似乎没有产生正确的输出。同样不,出于各种原因,我不希望使用密码。

有一些关键的细节没有被考虑。要应用RSA的数据必须编码为BigInteger x,在加密算法方面,第一条规则是永远不要自己实现现有算法。使用现有的、已知能正常工作的实现,例如Java提供的。