Golang, encrypting a string with AES and Base64

前端 未结 5 1941
青春惊慌失措
青春惊慌失措 2021-01-30 05:26

I\'m trying to encrypt some text inside a database to be loaded and decrypted during program startup.

I have tried a few methods, including a third party library https:/

5条回答
  •  借酒劲吻你
    2021-01-30 06:12

    Many have already provided nice answers. But as @PiersyP has pointed in the comments on @Intermernet 's answer, there's no need to base64 the text. So here it is without base64ing in case someone is in rush

    package main
    
    import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "errors"
        "fmt"
        "io"
        "log"
    )
    
    func main() {
        key := []byte("a very very very very secret key") // 32 bytes
        plaintext := []byte("some really really really long plaintext")
        fmt.Printf("%s\n", plaintext)
        ciphertext, err := encrypt(key, plaintext)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%0x\n", ciphertext)
        result, err := decrypt(key, ciphertext)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", result)
    }
    
    // See alternate IV creation from ciphertext below
    //var iv = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05}
    
    func encrypt(key, text []byte) ([]byte, error) {
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, err
        }
        ciphertext := make([]byte, aes.BlockSize + len(text))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            return nil, err
        }
        cfb := cipher.NewCFBEncrypter(block, iv)
        cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)
        return ciphertext, nil
    }
    
    func decrypt(key, text []byte) ([]byte, error) {
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, err
        }
        if len(text) < aes.BlockSize {
            return nil, errors.New("ciphertext too short")
        }
        iv := text[:aes.BlockSize]
        text = text[aes.BlockSize:]
        cfb := cipher.NewCFBDecrypter(block, iv)
        cfb.XORKeyStream(text, text)
        return text, nil
    }
    

提交回复
热议问题