github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/utils/hash/aes.go (about) 1 // Copyright © 2021 Alibaba Group Holding Ltd. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package hash 16 17 import ( 18 "bytes" 19 "crypto/aes" 20 "crypto/cipher" 21 "encoding/base64" 22 "fmt" 23 ) 24 25 const aesKey = "ZU9WbzRMVXRQZ2pzTGowR2hNWUpIZjRkWld4aWVRWko=" 26 27 func AesEncrypt(origData []byte) (string, error) { 28 key, err := base64.StdEncoding.DecodeString(aesKey) 29 if err != nil { 30 return "", fmt.Errorf("failed to decode key base64: %v", err) 31 } 32 block, err := aes.NewCipher(key) 33 if err != nil { 34 return "", err 35 } 36 blockSize := block.BlockSize() 37 origData = pkcs7Padding(origData, blockSize) 38 blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) 39 ciphertext := make([]byte, len(origData)) 40 blockMode.CryptBlocks(ciphertext, origData) 41 return base64.StdEncoding.EncodeToString(ciphertext), nil 42 } 43 44 func AesDecrypt(ciphertext []byte) (string, error) { 45 key, err := base64.StdEncoding.DecodeString(aesKey) 46 if err != nil { 47 return "", fmt.Errorf("failed to decode key base64: %v", err) 48 } 49 ciphertext, err = base64.StdEncoding.DecodeString(string(ciphertext)) 50 if err != nil { 51 return "", fmt.Errorf("failed to decode key base64: %v", err) 52 } 53 block, err := aes.NewCipher(key) 54 if err != nil { 55 return "", err 56 } 57 blockSize := block.BlockSize() 58 if len(ciphertext) < blockSize { 59 return "", fmt.Errorf("ciphertext short than block size") 60 } 61 62 plaintext := make([]byte, len(ciphertext)) 63 mode := cipher.NewCBCDecrypter(block, key[:blockSize]) 64 mode.CryptBlocks(plaintext, ciphertext) 65 plaintext = pkcs7UnPadding(plaintext) 66 return string(plaintext), nil 67 } 68 69 func pkcs7Padding(origData []byte, blockSize int) []byte { 70 padding := blockSize - len(origData)%blockSize 71 padText := bytes.Repeat([]byte{byte(padding)}, padding) 72 return append(origData, padText...) 73 } 74 75 func pkcs7UnPadding(origData []byte) []byte { 76 length := len(origData) 77 unPadding := int(origData[length-1]) 78 return origData[:(length - unPadding)] 79 }