728x90
반응형
AES(Advanced Encryption Standard)
- 비밀 키 하나로 메세지를 암호화하고, 다시 원래 메시지로 복호화한다. 이를 대칭키(symmetric) 방식이라 한다.
- 비밀 키의 비트 수에 따라 128, 192, 256으로 나누며, 각각의 바이트는 16바이트, 24바이트, 32바이트이다.
- 대부분 AES-256을 사용한다.
Encryption - 암호화
- 32바이트 길이의 키를 사용하여 새로운 AES 암호 생성한다.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
text := []byte("암호화")
key := []byte("passphrasewhichneedstobe32bytes!")
c, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
fmt.Println(err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
fmt.Println(err)
}
ciphertextByte := gcm.Seal(nonce, nonce, []byte(text), nil)
en := base64.StdEncoding.EncodeToString(ciphertextByte)
fmt.Println(en)
}
Decryption - 복호화
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"io/ioutil"
)
func main() {
key := []byte("passphrasewhichneedstobe32bytes!")
ciphertext, err := ioutil.ReadFile("myfile.data")
if err != nil {
fmt.Println(err)
}
c, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
fmt.Println(err)
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
fmt.Println(err)
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(plaintext))
}
728x90
반응형
'DevOps > GoLang' 카테고리의 다른 글
Go UUID/GUID generator (0) | 2023.01.10 |
---|---|
Go 구조체 & 포인터 & 슬라이스 & 맵 (0) | 2023.01.08 |
Go 반복문 & 제어문 (0) | 2023.01.08 |
Go 변수 & 상수 (1) | 2023.01.02 |
Go 데이터 타입 (0) | 2023.01.02 |
댓글