
在软件开发中,跨语言的代码迁移是常见的任务,尤其当涉及到加密解密等敏感功能时,其复杂性会显著增加。不同语言的加密库可能存在行为上的细微差异,例如默认的加密模式、填充方式以及对数据流的处理方式,这些都可能导致迁移失败。本文将以一个具体的案例为例,详细介绍如何将Java中基于AES加密并结合Bzip2压缩的解密逻辑,成功迁移到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);这段Java代码的核心逻辑包括:
最初的Golang迁移尝试如下:
立即学习“Java免费学习笔记(深入)”;
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)这个初始尝试存在几个关键问题:
要正确迁移,我们需要在Golang中实现与Java代码行为一致的AES ECB解密,并正确处理Bzip2流。
由于Java的Cipher.getInstance("AES")在没有指定模式时默认可能为ECB,且本案例中解密成功,我们可以推断出Java端使用了AES ECB模式。Golang标准库中没有直接提供cipher.NewECBDecrypter这样的接口,但crypto/aes包中的aes.NewCipher返回的cipher.Block接口本身就提供了ECB模式的核心功能:Decrypt(dst, src []byte)方法,该方法负责解密一个单块数据。因此,我们需要手动循环,按块进行解密。
以下是经过验证的Golang实现,它能够正确进行AES ECB解密并与Java代码兼容:
package main
import (
"bytes"
"compress/bzip2"
"crypto/aes"
"io"
"log"
"os"
)
// decryptAESECBStream performs AES ECB decryption on an io.Reader stream
// and writes the decrypted data to an io.Writer.
// It assumes the input stream contains data encrypted with AES ECB mode.
func decryptAESECBStream(keyString string, src io.Reader, dst io.Writer) error {
// 1. Create AES cipher block
c, err := aes.NewCipher([]byte(keyString))
if err != nil {
return err
}
// AES块大小为16字节
blockSize := aes.BlockSize
bufIn := make([]byte, blockSize) // Input buffer for encrypted block
bufOut := make([]byte, blockSize) // Output buffer for decrypted block
// Use a bytes.Buffer to collect all decrypted blocks
// This buffer will then be passed to bzip2.NewReader
decryptedBuffer := bytes.NewBuffer(make([]byte, 0))
// 2. Perform block-by-block decryption
for {
// Read one block from the source
n, err := io.ReadFull(src, bufIn) // io.ReadFull ensures exactly blockSize bytes are read or an error occurs
if err != nil {
if err == io.EOF {
// Reached end of stream, no more data to decrypt
break
}
if err == io.ErrUnexpectedEOF {
// Partial block read at the end, indicates incorrect padding or stream corruption
// For ECB, if no padding, this means the original data wasn't a multiple of block size.
// Handle this case based on the original padding scheme.
// In this specific problem, it seems no padding is applied, so partial blocks are errors.
log.Printf("Warning: Partial block read at EOF. This might indicate an issue with padding or stream length: %v", err)
break // Or return an error if partial blocks are strictly forbidden
}
return err // Other read errors
}
// Decrypt the block
c.Decrypt(bufOut, bufIn[:n]) // Decrypt only the actual bytes read
// Write the decrypted block to the temporary buffer
decryptedBuffer.Write(bufOut[:n])
}
// 3. Handle Bzip2 decompression
// bzip2.NewReader expects the full bzip2 stream, including the "BZ" header.
// The decryptedBuffer now contains the full decrypted bzip2 data (with "BZ" header).
zipReader := bzip2.NewReader(decryptedBuffer)
// 4. Copy decompressed data to the destination writer
_, err = io.Copy(dst, zipReader)
if err != nil {
return err
}
return nil
}
func main() {
// Example usage:
// Assume "encrypted_file.aes" is the encrypted file
// Assume "decrypted_output.txt" is where the decompressed data will be written
// Assume "your-secret-key-16" is your 16-byte AES key string
key := "your-secret-key-16" // Must be 16, 24, or 32 bytes for AES-128, AES-192, AES-256
encryptedFile, err := os.Open("encrypted_file.aes")
if err != nil {
log.Fatalf("Failed to open encrypted file: %v", err)
}
defer encryptedFile.Close()
outputFile, err := os.Create("decrypted_output.txt")
if err != nil {
log.Fatalf("Failed to create output file: %v", err)
}
defer outputFile.Close()
log.Println("Starting decryption and decompression...")
err = decryptAESECBStream(key, encryptedFile, outputFile)
if err != nil {
log.Fatalf("Decryption and decompression failed: %v", err)
}
log.Println("Decryption and decompression completed successfully.")
}代码说明:
在进行跨语言加密代码迁移时,需要特别注意以下几点:
以上就是从Java到Go:AES ECB解密与Bzip2流处理的迁移实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号