Golang, encrypting a string with AES and Base64

前端 未结 5 1924
青春惊慌失措
青春惊慌失措 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:00

    This is based on the NewCFBEncrypter / NewCFBDecrypter examples and seems to do what you require:

    EDIT: Based on Kluyg's comment regarding IV creation I've modified the example code to use the recommended method of creating the IV from the ciphertext same method as the linked example to create the IV from the ciphertext. (In production code the IV should be generated seperately each time. Thanks to RoundSparrow hilltx for pointing this out.)

    I think the problem you're encountering is due to an invalid key length, but I'm not 100% sure.

    package main
    
    import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "encoding/base64"
        "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
        }
        b := base64.StdEncoding.EncodeToString(text)
        ciphertext := make([]byte, aes.BlockSize+len(b))
        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:], []byte(b))
        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)
        data, err := base64.StdEncoding.DecodeString(string(text))
        if err != nil {
            return nil, err
        }
        return data, nil
    }
    

    Produces:

    some really really really long plaintext
    54618bd6bb10612a7b590c53192df214501e01b685540b012581a0ed9ff3ddaa1f4177cc6186b501fb8cce0c2eb764daff475aab724d4d33e614d7d89cf556d8512fd920018c090f
    some really really really long plaintext

    Playground

    Hope that helps to pin point the problem.

    0 讨论(0)
  • 2021-01-30 06:05

    It appears your order of operations are a bit backwards. Here is what you appear to be doing:

    ct = encrypt(encode(pt))
    pt = decode(decrypt(ct))
    

    It should look more like:

    ct = encode(encrypt(pt))
    pt = decrypt(decode(ct))
    

    The following works for me

    func Encrypt(key, text []byte) string {
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        ciphertext := make([]byte, aes.BlockSize+len(text))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(crand.Reader, iv); err != nil {
            panic(err)
        }
        cfb := cipher.NewCFBEncrypter(block, iv)
        cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)
        return encodeBase64(ciphertext)
    }
    
    
    func Decrypt(key []byte, b64 string) string {
        text := decodeBase64(b64)
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        if len(text) < aes.BlockSize {
            panic("ciphertext too short")
        }
        iv := text[:aes.BlockSize]
        text = text[aes.BlockSize:]
        cfb := cipher.NewCFBDecrypter(block, iv)
        cfb.XORKeyStream(text, text)
        return string(text)
    }
    
    0 讨论(0)
  • 2021-01-30 06:10

    Crypto is hard and the go libraries are perhaps not high level enough so it's easy to make mistakes.

    For anyone looking for an example of doing it right by an expert in the field (a security developer at CoreOS), this gives a good example of AES encryption (along with other common uses of crypto).

    https://github.com/gtank/cryptopasta

    0 讨论(0)
  • 2021-01-30 06:11

    Here is the working demo i just finished writing, it mostly uses code samples from the go document but it is tailored to do what most apps including my use case expects out of encryption methods.

    It use AES encryption. encrypt from string to base64 string. Easy to use on URL and dbs. decrypt from base64 string created above to original text.

    Simple text conversions everywhere.

    GIST: Here is the gist, please let me know if there are any need for the improvements.

    It's a simple go file, ready to be run.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题