Skip to content

Instantly share code, notes, and snippets.

@pinkumohikan
Last active July 1, 2021 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinkumohikan/5e35be711eeabbee19883258bc625b5d to your computer and use it in GitHub Desktop.
Save pinkumohikan/5e35be711eeabbee19883258bc625b5d to your computer and use it in GitHub Desktop.
GolangでAES256 CBCモードで暗号化 & 復号するサンプルコード
package library
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
type Encryption struct {
block cipher.Block
}
type EncryptedContext struct {
Iv []byte
CipherText []byte
}
func NewEncryption(key string) (*Encryption, error) {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
return &Encryption{
block: block,
}, nil
}
func (e *Encryption) Encrypt(message string) (*EncryptedContext, error) {
r := make([]byte, e.block.BlockSize())
if _, err := rand.Read(r); err != nil {
return nil, err
}
iv := r[:e.block.BlockSize()]
paddedMessage := e.paddingByPKCS5([]byte(message), e.block.BlockSize())
cipherText := make([]byte, len(paddedMessage))
encrypter := cipher.NewCBCEncrypter(e.block, iv)
encrypter.CryptBlocks(cipherText, paddedMessage)
return &EncryptedContext{
Iv: iv,
CipherText: cipherText,
}, nil
}
func (e *Encryption) Decrypt(cipherText []byte, iv []byte) string {
paddedMessage := make([]byte, len(cipherText))
decrypter := cipher.NewCBCDecrypter(e.block, iv)
decrypter.CryptBlocks(paddedMessage, cipherText)
return string(e.unPaddingByPKCS5(paddedMessage))
}
func (e *Encryption) paddingByPKCS5(message []byte, blockSize int) []byte {
needed := blockSize - len(message)%blockSize
padding := bytes.Repeat([]byte{byte(needed)}, needed)
return append(message, padding...)
}
func (e *Encryption) unPaddingByPKCS5(cipherText []byte) []byte {
onePadding := cipherText[len(cipherText)-1]
return cipherText[:len(cipherText)-int(onePadding)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment