Golang中的AES加密和Java中的解密 [英] AES Encryption in Golang and Decryption in Java

查看:522
本文介绍了Golang中的AES加密和Java中的解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Golang中编写了以下AES加密函数。

I have the following AES Encryption function written in Golang.

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)
}

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

I am struggling to understand the flow to decrypt the generated text using Java. Any help will be highly appreciated!

这是Scala代码,不确定它有什么问题。

Here is the Scala code, Not sure what's the problem with it.

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)
}


推荐答案

Java解码器(另请参阅在线可运行的演示,打开并单击执行):

Java decoder (see also online runnable demo, open and click "Execute"):

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

Kevin在评论中提供了此演示,我们可以看到以下结果:

Kevin in comments has offered this demo of the original Go encoder, where we can see the result of:

encrypt([]byte("0123456789abcdef"), "test text 123")

c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0 =

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

Let's see how the Java decoder above deals with that input:

String text = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=";
byte[] key = "0123456789abcdef".getBytes();
System.out.println(decode(text, key));

打印测试文本123

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

Scala version (online runnable demo):

def decode(input:String, key:String) = {
    val cipher = Cipher.getInstance("AES/CFB/NoPadding")
    val blockSize = cipher.getBlockSize()
    val keyBytes = key.getBytes()
    val inputArr = Base64.getUrlDecoder().decode(input)
    val skSpec = new SecretKeySpec(keyBytes, "AES")
    val iv = new IvParameterSpec(inputArr.slice(0, blockSize).toArray)
    val dataToDecrypt = inputArr.slice(blockSize, inputArr.size)
    cipher.init(Cipher.DECRYPT_MODE, skSpec, iv)
    new String(cipher.doFinal(dataToDecrypt.toArray))
}

def main(args: Array[String]) {
    print(decode("c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=", "0123456789abcdef"));
}

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

I think the only error in the Scala version is using Hex.decodeHex. You need a Base64 decoder that uses the URL-safe alphabet as described in RFC 4648, which java.util.Base64 offers (since Java 8) with its getUrlDecoder().

这篇关于Golang中的AES加密和Java中的解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆