gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/utils/utils.go (about) 1 package utils 2 3 import ( 4 "bytes" 5 "crypto/rand" 6 "encoding/pem" 7 "errors" 8 "fmt" 9 "io/ioutil" 10 "math/big" 11 ) 12 13 // ZeroByteSlice 0组成的32byte切片 14 func ZeroByteSlice() []byte { 15 return []byte{ 16 0, 0, 0, 0, 17 0, 0, 0, 0, 18 0, 0, 0, 0, 19 0, 0, 0, 0, 20 0, 0, 0, 0, 21 0, 0, 0, 0, 22 0, 0, 0, 0, 23 0, 0, 0, 0, 24 } 25 } 26 27 // PKCS7Padding 根据pkcs7标准填充明文 28 func PKCS7Padding(src []byte, blockSize int) []byte { 29 padding := blockSize - len(src)%blockSize 30 padtext := bytes.Repeat([]byte{byte(padding)}, padding) 31 return append(src, padtext...) 32 } 33 34 // PKCS7UnPadding 根据pkcs7标准去除填充 35 func PKCS7UnPadding(src []byte, blockSize int) ([]byte, error) { 36 length := len(src) 37 if length == 0 { 38 return nil, errors.New("invalid pkcs7 padding (len(padtext) == 0)") 39 } 40 unpadding := int(src[length-1]) 41 if unpadding > blockSize || unpadding == 0 { 42 return nil, fmt.Errorf("invalid pkcs7 padding (unpadding > BlockSize || unpadding == 0). unpadding: %d, BlockSize: %d", unpadding, blockSize) 43 } 44 45 pad := src[len(src)-unpadding:] 46 for i := 0; i < unpadding; i++ { 47 if pad[i] != byte(unpadding) { 48 return nil, errors.New("invalid pkcs7 padding (pad[i] != unpadding)") 49 } 50 } 51 52 return src[:(length - unpadding)], nil 53 } 54 55 // GetRandomBytes returns len random looking bytes 56 func GetRandomBytes(len int) ([]byte, error) { 57 if len < 0 { 58 return nil, errors.New("len must be larger than 0") 59 } 60 buffer := make([]byte, len) 61 n, err := rand.Read(buffer) 62 if err != nil { 63 return nil, err 64 } 65 if n != len { 66 return nil, fmt.Errorf("buffer not filled. Requested [%d], got [%d]", len, n) 67 } 68 return buffer, nil 69 } 70 71 // GetRandBigInt 随机生成序列号 72 // 73 // @return *big.Int 74 func GetRandBigInt() *big.Int { 75 sn, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) 76 if err != nil { 77 panic(err) 78 } 79 return sn 80 } 81 82 // ReadPemFromFile 从文件读取pem字节数组 83 // @param filePath 文件路径 84 // @return pemBytes pem字节数组 85 // @return err 86 //goland:noinspection GoUnusedExportedFunction 87 func ReadPemFromFile(filePath string) (pemBytes []byte, err error) { 88 fileBytes, err := ioutil.ReadFile(filePath) 89 if err != nil { 90 return nil, fmt.Errorf("could not read file [%s], error: %s", filePath, err) 91 } 92 b, _ := pem.Decode(fileBytes) 93 if b == nil { 94 return nil, fmt.Errorf("no pem content for file [%s]", filePath) 95 } 96 return fileBytes, nil 97 }