我在Visual Basic中有一个加密的字符串。 NET 2008,加密和解密的功能如下:

Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function

例如,使用此功能加密的单词“android”会给我结果“B3xogi / Qfsc =“

现在,我需要使用相同的密钥“key12345”从java解密字符串“B3xogi / Qfsc =“,其结果应为“android” ...任何人都知道如何执行此操作?

提前致谢。

最佳答案

使用Apache Commons Codec进行十六进制和base64编码/解码,可以使用以下代码:

KeySpec ks = new DESKeySpec("key12345".getBytes("UTF-8"));
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

IvParameterSpec iv = new IvParameterSpec(
        Hex.decodeHex("1234567890ABCDEF".toCharArray()));

Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);

byte[] decoded = cipher.doFinal(Base64.decodeBase64("B3xogi/Qfsc="));

System.out.println("Decoded: " + new String(decoded, "UTF-8"));

08-26 15:17