Go语言中如何使用AES加密和解密数据?

go语言中如何使用aes加密和解密数据?

go 中的 aes 加密方法

在 go 编程语言中,可以借助 crypto/aes 和 encoding/base64 库轻松地对数据进行 aes 加密。

以下代码展示了一种实现 aes/ecb/nopadding 加密的方法:

package main

import (
    "crypto/aes"
    "encoding/base64"
    "log"
)

func main() {
    str := []byte("406bf0ad11310101220213481000320000")
    key := []byte("er2fb6ts3ecx")

    encrypted, err := aesencryptecb(str, key)
    if err != nil {
        log.fatal(err)
    }

    decrypted, err := aesdecryptecb(encrypted, key)
    if err != nil {
        log.fatal(err)
    }

    log.println("encrypted:", encrypted)
    log.println("decrypted:", string(decrypted))
}

func aesencryptecb(origdata []byte, key []byte) (string, error) {
    cipher, err := aes.newcipher(generatekey(key))
    if err != nil {
        return "", err
    }
    length := (len(origdata) + aes.blocksize) / aes.blocksize
    plain := make([]byte, length*aes.blocksize)
    copy(plain, origdata)

    encrypted := make([]byte, len(plain))
    // block encryption
    for bs, be := 0, cipher.blocksize(); bs <= len(origdata); bs, be = bs+cipher.blocksize(), be+cipher.blocksize() {
        cipher.encrypt(encrypted[bs:be], plain[bs:be])
    }

    return base64.stdencoding.encodetostring(encrypted), nil
}

func aesdecryptecb(str string, key []byte) ([]byte, error) {
    encrypted, err := base64.stdencoding.decodestring(str)
    if err != nil {
        return nil, err
    }

    cipher, err := aes.newcipher(generatekey(key))
    if err != nil {
        return nil, err
    }
    decrypted := make([]byte, len(encrypted))
    for bs, be := 0, cipher.blocksize(); bs < len(encrypted); bs, be = bs+cipher.blocksize(), be+cipher.blocksize() {
        cipher.decrypt(decrypted[bs:be], encrypted[bs:be])
    }

    trim := 0
    if len(decrypted) > 0 {
        trim = len(decrypted) - int(decrypted[len(decrypted)-1])
    }
    return decrypted[:trim], nil
}

func generatekey(key []byte) (genkey []byte) {
    genkey = make([]byte, 16)
    copy(genkey, key)
    for i := 16; i < len(key); {
        for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
            genkey[j] ^= key[i]
        }
    }
    return genkey
}

以下是使用此方法加密和解密数据的示例:

str := []byte("406bf0ad11310101220213481000320000")
key := []byte("er2fb6ts3ecx")

encrypted, err := aesencryptecb(str, key)
if err != nil {
    log.fatal(err)
}

decrypted, err := aesdecryptecb(encrypted, key)
if err != nil {
    log.fatal(err)
}

log.println("encrypted:", encrypted)
log.println("decrypted:", string(decrypted))

输出:

Encrypted: rebZn7aj61hD3lfsUrhwFgVzPg4yYo9aseP/a4sNTRIh/Vtb0mziFfoHdOZBZ5uj
Decrypted: 406BF0AD11310101220213481000320000

以上就是Go语言中如何使用AES加密和解密数据?的详细内容,更多请关注www.sxiaw.com其它相关文章!