drxpt06820 2012-10-28 11:51
浏览 126
已采纳

将Java解密代码迁移到Golang

I'm struggling with the migration of Java code to Golang for the last few days and I am now stuck. This is the working Java code:

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

My implementation in 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)

What I know so far:

  • all error values omitted by _ are nil in this piece of code
  • the bzip2 header ("BZ") must be omitted for CBzip2InputStream, but not for bzip2.NewReader
  • the first 16 bytes read from instream in Java and golang are the same, starting with the 17th byte all bytes differ for whatever reason
  • 写回答

2条回答 默认 最新

  • doufen3134 2012-10-29 09:12
    关注

    CBizp2InputStream indeed uses AES ECB. This is a working implementation. I omitted error handling to make the code shorter:

    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)
    

    Additional explanation:

    • src is an io.Reader and dst is an io.Writer, both supplied to the decrypt function as arguments
    • keyString contains the secret key
    • I use i == 0 as breaking condition because err can or cannot be set to io.EOF in the last successful read (see golang io.Reader specification)

    Works perfectly. Implementing encryption should now be easy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?