java - 将Java解密代码迁移到Golang

标签 java go aes bzip2

过去几天我一直在努力将 Java 代码迁移到 Golang,现在我陷入了困境。这是有效的 Java 代码:

final Key k = new SecretKeySpec(keyString.getBytes(), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, k);

final InputStream in = new BufferedInputStream(new FileInputStream(fileNameToDecrypt));
final CipherInputStream instream = new CipherInputStream(in, c);

if (instream.read() != 'B') {
    System.out.println("Error");
}

if (instream.read() != 'Z') {
    System.out.println("Error");
}

final CBZip2InputStream zip = new CBZip2InputStream(instream);

我在 Golang 中的实现:

c, _ := aes.NewCipher([]byte(keyString))
// IV must be defined in golang
iv := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
d := cipher.NewCBCDecrypter(c, iv)

fi, _ := os.Open(fileNameToDecrypt)
stat, _ := fi.Stat()
enc := make([]byte, stat.Size())
dec := make([]byte, stat.Size())
fi.Read(enc)
d.CryptBlocks(dec, enc)
instream := bytes.NewBuffer(dec)
zip := bzip2.NewReader(instream)

目前我所知道的:

  • 所有被_省略的错误值在这段代码中都是nil
  • CBzip2InputStream 必须省略 bzip2 header (“BZ”),但bzip2.NewReader
  • 则不能
  • Java 和 golang 从 instream 中读取的前 16 个字节是相同的,从第 17 个字节开始所有字节都因某种原因而不同

最佳答案

CBizp2InputStream 确实使用了 AES ECB。这是一个有效的实现。我省略了错误处理以使代码更短:

c, _ := aes.NewCipher([]byte(keyString))
bufIn := make([]byte, 16)
bufOut := make([]byte, 16)
dec := bytes.NewBuffer(make([]byte, 0))
var i int

for {
    i, _ = src.Read(bufIn)
    if i == 0 {
        break
    }

    c.Decrypt(bufOut, bufIn)
    dec.Write(bufOut)
}

zip := bzip2.NewReader(dec)
io.Copy(dst, zip)

补充说明:

  • src 是一个 io.Reader,dst 是一个 io.Writer,两者都作为参数提供给解密函数
  • keyString 包含 key
  • 我使用 i == 0 作为中断条件,因为 err 在上次成功读取时可以或不能设置为 io.EOF(参见 golang io.Reader specification)<

完美运行。实现加密现在应该很容易。

关于java - 将Java解密代码迁移到Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108567/

相关文章:

gorilla Websocket - 读取错误 : repeated read on failed websocket connection

mysql - AES_Decrypt() 返回空值

node.js - 使用带有对称 key 加密的 unload 命令解密卸载的 s3 文件

java - 如何通过java和matlab控制运行.m(matlab)文件?

java - 嵌套 SQL 语句或 View ?什么是理想的?

java - 下拉描述或可展开 View

python-3.x - TypeError : can't concat bytes to str. Pycrypto Aes 加密

java - Android JSONObject 改组

go - 寻找有关如何在 golang 中创建 dll/so/dylib 的基本示例/资源

Go 的 git 库