Golang中的AES加密和Java中的解密

Rip*_*pul 5 java encryption scala aes go

我有以下用Golang编写的AES加密功能。

func encrypt(key []byte, text string) string {
    plaintext := []byte(text)

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

    return base64.URLEncoding.EncodeToString(ciphertext)
}
Run Code Online (Sandbox Code Playgroud)

我正在努力理解使用Java解密生成的文本的流程。任何帮助将不胜感激!

这是Scala代码,不知道这是什么问题。

def decode(input:String) = {
    val keyBytes = Hex.decodeHex("someKey".toCharArray)
    val inputWithoutPadding = input.substring(0,input.size - 2)
    val inputArr:Seq[Byte] = Hex.decodeHex(inputWithoutPadding.toCharArray)

    val skSpec = new SecretKeySpec(keyBytes, "AES")
    val iv = new IvParameterSpec(inputArr.slice(0,16).toArray)
    val dataToDecrypt = inputArr.slice(16,inputArr.size)

    val cipher = Cipher.getInstance("AES/CFB/NoPadding")
    cipher.init(Cipher.DECRYPT_MODE, skSpec, iv)
    cipher.doFinal(dataToDecrypt.toArray)
}
Run Code Online (Sandbox Code Playgroud)

Hug*_* M. 4

Java解码器(另见在线可运行演示,打开并单击“执行”):

\n\n
String decode(String base64Text, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {\n    byte[] inputArr = Base64.getUrlDecoder().decode(base64Text);\n    SecretKeySpec skSpec = new SecretKeySpec(key, "AES");\n    Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");\n    int blockSize = cipher.getBlockSize();\n    IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(inputArr, blockSize));\n    byte[] dataToDecrypt = Arrays.copyOfRange(inputArr, blockSize, inputArr.length);\n    cipher.init(Cipher.DECRYPT_MODE, skSpec, iv);\n    byte[] result = cipher.doFinal(dataToDecrypt);\n    return new String(result, StandardCharsets.UTF_8);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Kevin 在评论中提供了原始 Go 编码器的演示,我们可以在其中看到结果:

\n\n
encrypt([]byte("0123456789abcdef"), "test text 123")\n
Run Code Online (Sandbox Code Playgroud)\n\n

c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=

\n\n

让我们看看上面的 Java 解码器如何处理该输入:

\n\n
encrypt([]byte("0123456789abcdef"), "test text 123")\n
Run Code Online (Sandbox Code Playgroud)\n\n

打印test text 123\xe2\x9c\x94

\n\n
\n\n

Scala 版本(在线可运行演示):

\n\n
String text = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=";\nbyte[] key = "0123456789abcdef".getBytes();\nSystem.out.println(decode(text, key));\n
Run Code Online (Sandbox Code Playgroud)\n\n

我认为 Scala 版本中唯一的错误是使用Hex.decodeHex. 您需要一个使用 URL 安全字母表的 Base64 解码器,如 RFC 4648 中所述,RFC 4648java.util.Base64提供(自 Java 8 起)及其getUrlDecoder().

\n