【发布时间】:2012-10-17 23:55:00
【问题描述】:
在过去的几天里,我一直在努力将 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 标头(“BZ”),bzip2.NewReader则不能 - 在 Java 和 golang 中从
instream读取的前 16 个字节是相同的,从第 17 个字节开始所有字节因任何原因而不同
【问题讨论】:
-
如果前 16 个字节相同而其余字节不同,我怀疑这两种实现使用不同的块链接模式:en.wikipedia.org/wiki/Block_cipher_modes_of_operation。看来您在 Golang 中使用 CBC,不确定 Java 中的默认值是什么。
-
我尝试了 golang 中所有可用的方法。 CBC 是唯一至少前几个字节被正确解密的。如果没有提供 IV,Java 可能默认使用 ECB,我会检查一下,谢谢提示。