gpt4 book ai didi

java - RSA Cypher VisualBasic 到 Java

转载 作者:行者123 更新时间:2023-11-30 09:00:34 25 4
gpt4 key购买 nike

我在用 Java 加密某些字符串时遇到问题。我需要用与此 VisualBasic 代码相同的方式对它们进行加密:

 Public Function Encrypt(ByRef EncryptionKeyPair As KeyPair, ByVal PlainText As String) As String
//Use Public Key to encrypt
m_objRSA.FromXmlString(EncryptionKeyPair.PublicKey.Key)

//Get Modulus Size and compare it to length of PlainText
// If Length of PlainText > (Modulus Size - 11), then PlainText will need to be broken into segments of size (Modulus Size - 11)
//Each of these segments will be encrypted separately
// and will return encrypted strings equal to the Modulus Size (with at least 11 bytes of padding)
//When decrypting, if the EncryptedText string > Modulus size, it will be split into segments of size equal to Modulus Size
//Each of these EncryptedText segments will be decrypted individually with the resulting PlainText segments re-assembled.

Dim intBlockSize As Integer = GetModulusSize(EncryptionKeyPair.PublicKey.Key) - 11
Dim strEncryptedText As String = ""

While Len(PlainText) > 0
If Len(PlainText) > intBlockSize Then
strEncryptedText = strEncryptedText & EncryptBlock(Left(PlainText, intBlockSize))
PlainText = Right(PlainText, Len(PlainText) - intBlockSize)
Else
strEncryptedText = strEncryptedText & EncryptBlock(PlainText)
PlainText = ""
End If
End While

Return strEncryptedText
End Function


Private Function EncryptBlock(ByRef TheRSAProvider As RSACryptoServiceProvider, ByVal strIn As String) As String
Return ByteArrayAsString(TheRSAProvider.Encrypt(StringAsByteArray(strIn), False))
End Function

Private Function GetModulusSize(ByVal intKeySize As Integer) As Integer
//KeySize is in Bits - so divide by 8 to get # of bytes
Return intKeySize / 8
End Function

我已经在互联网上搜索过了,但我还没有找到这样的东西。我有来自模数和指数的公钥,我正在这样做:

byte[] expBytes = Base64.decode(exponent.trim());
byte[] modBytes = Base64.decode(modulus.trim());

BigInteger modules = new BigInteger(1, modBytes);
BigInteger exponents = new BigInteger(1, expBytes);

KeyFactory factory = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponents);
PublicKey pubKey = factory.generatePublic(pubSpec);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted =cipher.doFinal(field.getBytes("UTF-16LE"));
String string = new String(encrypted);

结果不正确,因为我没有对模数大小 - 11 做任何事情。你能解释一下我如何在 Java 中做到这一点吗?

谢谢。

最佳答案

模数大小不是问题。问题更有可能是您期望生成相同的值。它们不是,甚至不在 VB 代码或 Java 代码中(运行代码片段两次!)。 RSA PKCS#1 v1.5 填充包含随机数,确保加密始终产生不同的值。顺便说一下,这与 OAEP 填充相同。

请注意,您可能想要查看 OAEP 模式和混合密码系统,而不是您现在正在做的事情。然后你会更安全,你将能够处理任何大小的数据,尽管密文的数量当然会更大。

关于java - RSA Cypher VisualBasic 到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26739249/

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