Last active
August 28, 2024 04:40
-
-
Save yingray/57fdc3264b1927ef0f984b533d63abab to your computer and use it in GitHub Desktop.
Golang: aes-256-cbc 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 | |
import ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"encoding/hex" | |
"fmt" | |
) | |
func main() { | |
key := "12345678901234567890123456789012" | |
iv := "1234567890123456" | |
plaintext := "abcdefghijklmnopqrstuvwxyzABCDEF" | |
fmt.Printf("Result: %v\n", Ase256(plaintext, key, iv, aes.BlockSize)) | |
} | |
func Ase256(plaintext string, key string, iv string, blockSize int) string { | |
bKey := []byte(key) | |
bIV := []byte(iv) | |
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext)) | |
block, _ := aes.NewCipher(bKey) | |
ciphertext := make([]byte, len(bPlaintext)) | |
mode := cipher.NewCBCEncrypter(block, bIV) | |
mode.CryptBlocks(ciphertext, bPlaintext) | |
return hex.EncodeToString(ciphertext) | |
} | |
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
@robi23-gunawan Here you go https://gist.github.com/awadhwana/9c95377beba61293390c5fd23a3bb1df