Golang, encrypting a string with AES and Base64

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

提交回复
热议问题