Skip to content

Instantly share code, notes, and snippets.

@ken5scal
Last active October 13, 2018 01:56
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 ken5scal/3c9cbfac4c73ce476c838c4bb5b30109 to your computer and use it in GitHub Desktop.
Save ken5scal/3c9cbfac4c73ce476c838c4bb5b30109 to your computer and use it in GitHub Desktop.
GoでAESアルゴリズム(CBCモード)を使った実装をする ref: https://qiita.com/ken5scal/items/22efdace02b199f7007f
func EncryptByCBCMode(key []byte, plainText string) ([]byte, error) {
if len(plainText) % aes.BlockSize != 0 {
panic("Plain text must be multiple of 128bit")
}
block, err := aes.NewCipher(key); if err != nil {
return nil, err
}
cipherText := make([]byte, aes.BlockSize + len(plainText)) // 初期化ベクトルを保存するためにaes.BlockSizeを加えている
iv := cipherText[:aes.BlockSize] // Unique iv is required
_, err = rand.Read(iv); if err != nil {
return nil, err
}
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(cipherText[aes.BlockSize:], []byte(plainText))
return cipherText, nil
}
func DecryptByCBCMode(key []byte, cipherText []byte) (string ,error) {
block , err := aes.NewCipher(key); if err != nil {
return "", err
}
if len(cipherText) < aes.BlockSize {
panic("cipher text must be longer than blocksize")
} else if len(cipherText) % aes.BlockSize != 0 {
panic("cipher text must be multiple of blocksize(128bit)")
}
iv := cipherText[:aes.BlockSize] // assuming iv is stored in the first block of ciphertext
cipherText = cipherText[aes.BlockSize:]
plainText := make([]byte, len(cipherText))
cbc := cipher.NewCBCDecrypter(block, iv)
cbc.CryptBlocks(plainText, cipherText)
fmt.Println(plainText)
return string(plainText), nil
}
func main() {
cipherText, _ = EncryptByCBCMode(key, "1234567891234567") // 16bye
fmt.Println(cipherText)
cipherText, _ = EncryptByCBCMode(key, "12345678912345671234123412341234") // 32byte
fmt.Println(cipherText)
// iv(32 byte) + 16byte
plainText, _ = DecryptByCBCMode(key, cipherText)
fmt.Println(plainText)
// 12345678912345671234123412341234
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment