Golang AES加密

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "fmt"
    "os"
)

var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}

func main() {
    //password length must be under 30
    password := []byte("thisisthepassword")
    //key string
    key := "s8*WQ0@KO#CN*raoua8ofCTx*oxqCk46"

    ciphercode := Encrypt(key, password)
    Decrypt(key, ciphercode)

}

func Encrypt(key string, password []byte) []byte {
    //create aes
    c, err := aes.NewCipher([]byte(key))
    if err != nil {
        fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key), err)
        os.Exit(-1)
    }

    //encrypt string
    cfb := cipher.NewCFBEncrypter(c, commonIV)
    ciphertext := make([]byte, len(password))
    cfb.XORKeyStream(ciphertext, password)
    return ciphertext
}

func Decrypt(key string, ciphercode []byte) []byte {
    //create aes
    c, err := aes.NewCipher([]byte(key))
    if err != nil {
        fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key), err)
        os.Exit(-1)
    }

    //decrypt string
    cfbdec := cipher.NewCFBDecrypter(c, commonIV)
    password := make([]byte, 30)
    cfbdec.XORKeyStream(password, ciphercode)
    return password
}
下面是一个使用golang中的crypto库进行AES GCM模式加密文件的示例代码: ```go package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" "io/ioutil" "os" ) func main() { // 读取原始文件 data, err := ioutil.ReadFile("plaintext.txt") if err != nil { panic(err) } // 随机生成16字节的密钥 key := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, key); err != nil { panic(err) } // 创建GCM加密器 block, err := aes.NewCipher(key) if err != nil { panic(err) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err) } // 随机生成12字节的IV iv := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } // 使用GCM加密数据 ciphertext := aesgcm.Seal(nil, iv, data, nil) // 将密钥和IV写入文件开头 output := append(key, iv...) // 将加密数据写入文件尾部 output = append(output, ciphertext...) // 将加密结果写入文件 err = ioutil.WriteFile("ciphertext.bin", output, 0644) if err != nil { panic(err) } fmt.Println("Encryption complete.") } ``` 这个示例代码中,我们首先读取要加密的文件的内容。然后,我们使用crypto库中提供的`aes.NewCipher`函数创建一个AES加密器,并使用这个加密器创建一个GCM加密器。接下来,我们随机生成一个16字节的密钥和一个12字节的IV,然后使用GCM加密器对原始数据进行加密。最后,我们将密钥和IV写入加密文件的开头,将加密数据写入文件的尾部。 注意,在实际应用中,我们应该使用更加安全的方式来生成密钥和IV,例如使用密码学安全的伪随机数生成器。此外,我们也应该对加密文件进行适当的保护,例如使用密码或者其他的访问控制措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值