|
| 1 | +package AtlasInsideAES |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "crypto/aes" |
| 6 | + "crypto/cipher" |
| 7 | + "crypto/sha1" |
| 8 | + b64 "encoding/base64" |
| 9 | + "golang.org/x/crypto/pbkdf2" |
| 10 | +) |
| 11 | + |
| 12 | +const IterationCount = 65536 |
| 13 | +const SaltLength = 16 |
| 14 | +const KeyLength = 16 |
| 15 | + |
| 16 | +func setKey(key []byte) (cipher.Block, []byte, error) { |
| 17 | + h := sha1.New() |
| 18 | + h.Write(key) |
| 19 | + salt := h.Sum(nil) |
| 20 | + keyEnc := pbkdf2.Key(key, salt, IterationCount, KeyLength, sha1.New) |
| 21 | + block, err := aes.NewCipher(keyEnc) |
| 22 | + if err != nil { |
| 23 | + return nil, nil, err |
| 24 | + } |
| 25 | + return block, salt[:SaltLength], nil |
| 26 | +} |
| 27 | + |
| 28 | +func AESEncrypt(src string, key []byte) (string, error) { |
| 29 | + if len(src) == 0 { |
| 30 | + return "", &InvalidEncryptedDataError{"Invalid crypto"} |
| 31 | + } |
| 32 | + blkEncrypt, ivEncrypt, err := setKey(key) |
| 33 | + if err != nil { |
| 34 | + return "", &InvalidAESKeyError{"Invalid crypto"} |
| 35 | + } |
| 36 | + ecb := cipher.NewCBCEncrypter(blkEncrypt, ivEncrypt) |
| 37 | + content := []byte(src) |
| 38 | + content = PKCS5Padding(content, blkEncrypt.BlockSize()) |
| 39 | + crypted := make([]byte, len(content)) |
| 40 | + ecb.CryptBlocks(crypted, content) |
| 41 | + base64 := b64.StdEncoding.EncodeToString(crypted) |
| 42 | + return base64, nil |
| 43 | +} |
| 44 | + |
| 45 | +func AESDecrypt(crypt string, key []byte) (string, error) { |
| 46 | + encryptedData, _ := b64.StdEncoding.DecodeString(crypt) |
| 47 | + if len(crypt) == 0 { |
| 48 | + return "", &InvalidPassphraseError{"Invalid crypto"} |
| 49 | + } |
| 50 | + blk, iv, err := setKey(key) |
| 51 | + if err != nil { |
| 52 | + return "", &InvalidAESKeyError{"Invalid crypto"} |
| 53 | + } |
| 54 | + ecb := cipher.NewCBCDecrypter(blk, iv) |
| 55 | + decrypted := make([]byte, len(encryptedData)) |
| 56 | + ecb.CryptBlocks(decrypted, encryptedData) |
| 57 | + return string(PKCS5Trimming(decrypted)), nil |
| 58 | +} |
| 59 | + |
| 60 | +func PKCS5Padding(ciphertext []byte, blockSize int) []byte { |
| 61 | + padding := blockSize - len(ciphertext)%blockSize |
| 62 | + padtext := bytes.Repeat([]byte{byte(padding)}, padding) |
| 63 | + return append(ciphertext, padtext...) |
| 64 | +} |
| 65 | + |
| 66 | +func PKCS5Trimming(encrypt []byte) []byte { |
| 67 | + padding := encrypt[len(encrypt)-1] |
| 68 | + return encrypt[:len(encrypt)-int(padding)] |
| 69 | +} |
0 commit comments