Last active
April 19, 2024 07:31
-
-
Save awadhwana/9c95377beba61293390c5fd23a3bb1df to your computer and use it in GitHub Desktop.
Golang: aes-256-cbc ecrypt/decrypt examples (with iv, blockSize)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Working example: https://goplay.space/#Sa7qCLm6w65 | |
import ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"encoding/hex" | |
"fmt" | |
) | |
func main() { | |
key := "12345678901234567890123456789012" | |
iv := "1234567890123456" | |
plaintext := "abcdefghijklmnopqrstuvwxyzABCDEF" | |
fmt.Println("Data to encode: ", plaintext) | |
cipherText := fmt.Sprintf("%v", Ase256Encode(plaintext, key, iv, aes.BlockSize)) | |
fmt.Println("Encode Result:\t", cipherText) | |
fmt.Println("Decode Result:\t", Ase256Decode(cipherText, key, iv)) | |
} | |
func Ase256Encode(plaintext string, key string, iv string, blockSize int) string { | |
bKey := []byte(key) | |
bIV := []byte(iv) | |
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext)) | |
block, err := aes.NewCipher(bKey) | |
if err != nil { | |
panic(err) | |
} | |
ciphertext := make([]byte, len(bPlaintext)) | |
mode := cipher.NewCBCEncrypter(block, bIV) | |
mode.CryptBlocks(ciphertext, bPlaintext) | |
return hex.EncodeToString(ciphertext) | |
} | |
func Ase256Decode(cipherText string, encKey string, iv string) (decryptedString string) { | |
bKey := []byte(encKey) | |
bIV := []byte(iv) | |
cipherTextDecoded, err := hex.DecodeString(cipherText) | |
if err != nil { | |
panic(err) | |
} | |
block, err := aes.NewCipher(bKey) | |
if err != nil { | |
panic(err) | |
} | |
mode := cipher.NewCBCDecrypter(block, bIV) | |
mode.CryptBlocks([]byte(cipherTextDecoded), []byte(cipherTextDecoded)) | |
return string(cipherTextDecoded) | |
} | |
func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte { | |
padding := (blockSize - len(ciphertext)%blockSize) | |
padtext := bytes.Repeat([]byte{byte(padding)}, padding) | |
return append(ciphertext, padtext...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi all
I wanted to encrypt and decrypt using a key of length 43 which I am getting from hashicorp vault
https://goplay.space/#C3TFPoaDmeb
how can I make this work? can you pls suggest