github.heygears.com/openimsdk/tools@v0.0.49/utils/encrypt/encryption.go (about) 1 // Copyright © 2023 OpenIM. All rights reserved. 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 encrypt 16 17 import ( 18 "bytes" 19 "crypto/aes" 20 "crypto/cipher" 21 "crypto/md5" 22 "encoding/hex" 23 "github.com/openimsdk/tools/errs" 24 ) 25 26 // Md5 returns the md5 hash of the input string. 27 func Md5(s string, salt ...string) string { 28 h := md5.New() 29 h.Write([]byte(s)) 30 if len(salt) > 0 { 31 h.Write([]byte(salt[0])) 32 } 33 34 cipher := h.Sum(nil) 35 return hex.EncodeToString(cipher) 36 } 37 38 // AesEncrypt encrypts the data with the key using AES encryption. 39 func AesEncrypt(data []byte, key []byte) ([]byte, error) { 40 block, err := aes.NewCipher(key) 41 if err != nil { 42 return nil, errs.WrapMsg(err, "NewCipher failed", "key", key) 43 } 44 blockSize := block.BlockSize() 45 encryptBytes := pkcs7Padding(data, blockSize) 46 crypted := make([]byte, len(encryptBytes)) 47 blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) 48 blockMode.CryptBlocks(crypted, encryptBytes) 49 return crypted, nil 50 } 51 52 // AesDecrypt decrypts the data with the key using AES encryption. 53 func AesDecrypt(data []byte, key []byte) ([]byte, error) { 54 block, err := aes.NewCipher(key) 55 if err != nil { 56 return nil, errs.WrapMsg(err, "NewCipher failed", "key", key) 57 } 58 blockSize := block.BlockSize() 59 blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) 60 crypted := make([]byte, len(data)) 61 blockMode.CryptBlocks(crypted, data) 62 crypted, err = pkcs7UnPadding(crypted) 63 if err != nil { 64 return nil, err 65 } 66 return crypted, nil 67 } 68 69 // pkcs7Padding PKCS7 padding 70 func pkcs7Padding(data []byte, blockSize int) []byte { 71 padding := blockSize - len(data)%blockSize 72 padText := bytes.Repeat([]byte{byte(padding)}, padding) 73 return append(data, padText...) 74 } 75 76 // pkcs7UnPadding PKCS7 unpadding 77 func pkcs7UnPadding(data []byte) ([]byte, error) { 78 length := len(data) 79 if length == 0 { 80 return nil, errs.New("data is nil") 81 } 82 unPadding := int(data[length-1]) 83 return data[:(length - unPadding)], nil 84 }