过去几天我一直在努力将 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/