将Java解密代码迁移到Golang
在过去的几天里,我一直在努力将Java代码迁移到Golang,现在我陷入了困境。这是工作的Java代码:将Java解密代码迁移到Golang,java,go,aes,bzip2,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 FileInputStre
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
- 对于
,必须省略bzip2头(“BZ”),但对于CBzip2InputStream
bzip2.NewReader
- 在Java和golang中,从
读取的前16个字节是相同的,从第17个字节开始,所有字节因任何原因而不同instream
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,两者都作为参数提供给decrypt函数
- keyString包含密钥
- 我使用
作为中断条件,因为上次成功读取时I==0
可以或不能设置为io.EOF(请参阅)err
工作完美。现在实现加密应该很容易。我正在尝试相同的方法,但使用三重加密模式。我找到了ECB的代码,因为它没有在go加密库中实现,因为它不安全。然而,当初始化三重DES密码时,我得到一个密钥长度错误,我必须使用某个密钥。引发错误的密码库中的代码为:
// NewTripleDESCipher creates and returns a new cipher.Block.
func NewTripleDESCipher(key []byte) (cipher.Block, error) {
if len(key) != 24 {
return nil, KeySizeError(len(key))
}
我能做些什么来克服这个问题?请注意,在Java中我没有这个问题。如果前16个字节相同,其余的则不同,我怀疑这两个实现使用的是不同的块链接模式:。看起来您在Golang中使用CBC,不确定Java中的默认值是多少。我尝试了Golang中所有可用的方法。CBC是唯一一个至少前几个字节被正确解密的系统。如果没有提供IV,Java可能默认使用ECB,我会检查一下,谢谢你的提示。最有可能的是,该键在那里填充了例如0个字节。