Encryption 将Python AES加密路由移植到Golang

Encryption 将Python AES加密路由移植到Golang,encryption,go,cryptography,aes,Encryption,Go,Cryptography,Aes,我正在尝试移植以下Python AES文件加密例程: def derive_key_and_iv(password, salt, key_length, iv_length): d = d_i = '' while len(d) < key_length + iv_length: d_i = md5(d_i + password + salt).digest() d += d_i return d[:key_length], d[ke

我正在尝试移植以下Python AES文件加密例程:

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]


def encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = Random.new().read(bs - len('Salted__'))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        out_file.write(cipher.encrypt(chunk))


def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    print(bs)
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)
def派生密钥和iv(密码、salt、密钥长度、iv长度):
d=d_i=''
而len(d)
我已经编写了以下Go例程,但我不太能够让它工作。我试图让加密例程在Go中工作,以便调用Python和C中的解密的调用方使用,因此我真正感兴趣的是如何让我的Golang加密例程工作,但为了清晰起见,我已经包含了所有Python位

我目前的围棋程序如下所示:

package main
import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "errors"
    "fmt"
    "io"
    "log"     
    "crypto/md5"  
    "os"
    )


func pyEncrypt(password []byte, pathToInFile string, pathToOutFile string){
    bs := int(aes.BlockSize)
    salt := make([]byte, aes.BlockSize - len("Salted__")) 
    _, err := rand.Read(salt)
    if err != nil {panic(err)}

    key, iv := deriveKeyAndIV(password, salt, bs)   
    block, err := aes.NewCipher(key)
    if err != nil {panic(err)}

    cfb := cipher.NewCFBEncrypter(block, iv)

    fin, err := os.Open(pathToInFile)
    if err != nil {panic(err)}
    defer fin.Close()

    fout, err := os.Create(pathToOutFile)
    if err != nil {panic(err)}
    defer fout.Close()

    _, err = fout.Write([]byte("Salted__")) 
    if err != nil {panic(err)}
    _, err = fout.Write(salt)
    if err != nil {panic(err)}

    for true{
        ciphertext := make([]byte, 1024 *bs)
        chunk := make([]byte, 1024 * bs)
        _, err := fin.Read(chunk)
        if err == io.EOF{
        break
        }else if err != nil{
            panic(err)
        }
        cfb.XORKeyStream(ciphertext, chunk)     
        fout.Write(ciphertext)
    }
}


func deriveKeyAndIV(password []byte, salt []byte, bs int) ([]byte, []byte) {
    var digest []byte
    hash := md5.New()
    out := make([]byte, 32 + bs) //right now I'm just matching the default key size (32) from the python script so 32 represents the default from python
    for i := 0; i < 32 + bs ; i += len(digest) {
        hash.Reset()
        hash.Write(digest)
        hash.Write(password)
        hash.Write(salt)
        digest = hash.Sum(digest[:0])
        copy(out[i:], digest)
    }
    return out[:32], out[32:32+bs] //matching the default key size from Python as that is what the application uses
}

func main() {
    pwd := []byte("test123")

    pyEncrypt(pwd, "/home/chris/pt.txt", "/home/chris/genc.txt")    
}
主程序包
进口(
“加密/aes”
“加密/密码”
“加密/兰德”
“编码/base64”
“错误”
“fmt”
“io”
“日志”
“加密/md5”
“操作系统”
)
func pyEncrypt(密码[]字节,路径文件字符串,路径输出文件字符串){
bs:=int(aes块大小)
salt:=make([]字节,aes.BlockSize-len(“salt_u__;”))
_,err:=rand.Read(salt)
如果err!=nil{panic(err)}
密钥,iv:=deriveKeyAndIV(密码,salt,bs)
块,错误:=aes.NewCipher(密钥)
如果err!=nil{panic(err)}
cfb:=加密机newCfB加密机(块,iv)
fin,err:=os.Open(路径文件)
如果err!=nil{panic(err)}
延迟财务结束()
fout,err:=os.Create(路径输出文件)
如果err!=nil{panic(err)}
延迟fout.Close()
_,err=fout.Write([]字节(“盐渍”)
如果err!=nil{panic(err)}
_,err=fout.Write(salt)
如果err!=nil{panic(err)}
真的{
密文:=make([]字节,1024*bs)
区块:=生成([]字节,1024*bs)
_,err:=fin.Read(块)
如果err==io.EOF{
打破
}否则,如果错误!=零{
恐慌(错误)
}
XORKeyStream(密文,块)
四写(密文)
}
}
func deriveKeyAndIV(密码[]字节,salt[]字节,bs int)([]字节,[]字节){
变量摘要[]字节
哈希:=md5.New()
out:=make([]字节,32+bs)//现在我正在匹配python脚本中的默认密钥大小(32),因此32表示python中的默认值
对于i:=0;i<32+bs;i+=len(摘要){
hash.Reset()
hash.Write(摘要)
hash.Write(密码)
hash.Write(salt)
digest=hash.Sum(digest[:0])
抄送(出[i:],摘要)
}
return out[:32],out[32:32+bs]//匹配Python中的默认密钥大小,因为这是应用程序使用的
}
func main(){
pwd:=[]字节(“test123”)
pyEncrypt(pwd,“/home/chris/pt.txt”,“/home/chris/genc.txt”)
}

现在它运行,lol,生成一个加密文件,看起来正确,Python“解密”没有错误,但它生成乱码,实际上不会生成明文。Python例程是独立工作的,但我无法获得Python decrypt可以解密的Golang encrypt生成的输出。为了与调用者兼容,我必须匹配Python加密例程。你知道我在Golang加密程序中做错了什么吗?非常感谢您的帮助。

以下是正在运行的加密例程:

func pyEncrypt(password string, pathToInFile string, pathToOutFile string){
    bs := int(aes.BlockSize)
    salt := make([]byte, aes.BlockSize - len("Salted__")) 
    _, err := rand.Read(salt)
    if err != nil {panic(err)}

    key, iv := deriveKeyAndIV([]byte(password), salt, bs)   
    block, err := aes.NewCipher(key)
    if err != nil {panic(err)}

    cbc := cipher.NewCBCEncrypter(block, iv)

    fin, err := os.Open(pathToInFile)
    if err != nil {panic(err)}
    defer fin.Close()

    fout, err := os.Create(pathToOutFile)
    if err != nil {panic(err)}
    defer fout.Close()

    _,err = fout.Write([]byte("Salted__"))
    if err != nil {panic(err)}
    _,err = fout.Write(salt)
    if err != nil {panic(err)}

    for true{
        chunk := make([]byte, 1024 * bs)

        n,err := fin.Read(chunk)
        if err == io.EOF{
        break
        }else if err != nil{
            panic(err)
        }

        if n == 0 || n % bs != 0 {//need to pad up to block size :bs
            paddingLength := (bs - n % bs) 
            paddingChr := []byte(string(rune(paddingLength)))
            paddingBytes := make([]byte, paddingLength)

            for i := 0; i < paddingLength; i++{
                paddingBytes[i] = paddingChr[0]
            }

            chunk = append(chunk[0:n], []byte(paddingBytes)...)
        }else{
            chunk = chunk[0:n]//no padding needed           
        }

        ciphertext := make([]byte, len(chunk))
        cbc.CryptBlocks(ciphertext,chunk)
        fout.Write(ciphertext)
    }
}
func pyEncrypt(密码字符串、路径文件字符串、路径输出文件字符串){
bs:=int(aes块大小)
salt:=make([]字节,aes.BlockSize-len(“salt_u__;”))
_,err:=rand.Read(salt)
如果err!=nil{panic(err)}
密钥,iv:=deriveKeyAndIV([]字节(密码),salt,bs)
块,错误:=aes.NewCipher(密钥)
如果err!=nil{panic(err)}
cbc:=cipher.NewCBCEncrypter(块,iv)
fin,err:=os.Open(路径文件)
如果err!=nil{panic(err)}
延迟财务结束()
fout,err:=os.Create(路径输出文件)
如果err!=nil{panic(err)}
延迟fout.Close()
_,err=fout.Write([]字节(“盐渍”)
如果err!=nil{panic(err)}
_,err=fout.Write(salt)
如果err!=nil{panic(err)}
真的{
区块:=生成([]字节,1024*bs)
n、 错误:=fin.Read(块)
如果err==io.EOF{
打破
}否则,如果错误!=零{
恐慌(错误)
}
如果n==0 | | n%bs!=0{//需要填充到块大小:bs
填充长度:=(bs-n%bs)
paddingChr:=[]字节(字符串(符文(paddingLength)))
paddingBytes:=make([]字节,paddingLength)
对于i:=0;i