오늘도 한 뼘 더
[Golang] AES 암호화, 복호화 (Encrypt, Decrypt) 본문
728x90
반응형
# 배경
민감한 정보의 경우 암호화를 해서 저장을 해야 하는데 암호화를 하는 코드를 작성해보도록 하자
# AES 암호화
AES는 Advanced Encryption Standard의 약자로 고급 암호화 표준이라는 의미이다.
암호화 블록의 크기가 128bit이고 암호화 키의 길이가 128, 192, 256 bit인 세 종류로 나뉜다.
## 암호화 코드
func Encrypt(key, text string) (string, error) {
plainText := []byte(text)
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", nil
}
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
encryptedText := base64.URLEncoding.EncodeToString(cipherText)
return encryptedText, nil
}
## 복호화 코드
func Decrypt(key, text string) (string, error) {
if text == "" {
return "", nil
}
cipherText, err := base64.URLEncoding.DecodeString(text)
if err != nil {
return "", err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
if len(cipherText) < aes.BlockSize {
err = errors.New("cipher text block size is too short")
return "", err
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)
return string(cipherText), nil
}
728x90
반응형
'Study > Go' 카테고리의 다른 글
[Go] error="sql: expected 4 destination arguments in Scan, not 1" (0) | 2022.12.20 |
---|---|
[Golang] DB(MySQL) 연결 시 timezone 설정 (0) | 2022.09.30 |
[Golang] Golang CI Lint 설치하고 사용하기 (0) | 2022.09.20 |
[Golang] AWS SNS(Simple Notification Service) 주제 리스트 조회하기 (0) | 2022.09.06 |
[Golang] net/http 패키지로 API 호출하기 (0) | 2022.09.03 |
Comments