RSA Cypher VisualBasic到Java

时间:2014-11-04 15:45:20

标签: java vb.net encryption rsa

我在使用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做到这一点?

谢谢。

1 个答案:

答案 0 :(得分:2)

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

请注意,您可能希望查看OAEP模式和混合密码系统,而不是现在正在执行的操作。然后你会更安全,你将能够处理任何大小的数据,虽然密文的数量当然会更大。