2
我在加密Java中的一些字符串時遇到問題。我需要比這個的VisualBasic代碼做加密它們以同樣的方式:RSA Cypher VisualBasic到Java
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中這樣做?
謝謝。
我知道它會產生總是不同的值。問題是我將Java加密字符串發送到Visual Basic Web服務,並且無法解密它。解密遵循該模數大小規則。我剛給了加密的例子,你需要解密代碼嗎? – DiogoPinheiro 2014-11-05 09:22:47
不一定,但你應該更新你的問題,因爲「結果不正確」列出有史以來最糟糕的錯誤描述。 – 2014-11-05 09:29:50
我認爲標題和描述很清楚。我需要的只是在Java中實現這種可視化的基本加密。 – DiogoPinheiro 2014-11-05 12:03:27