github.com/suiyunonghen/DxCommonLib@v0.5.3/cryptlib/des.go (about) 1 package cryptlib 2 3 import ( 4 "crypto/des" 5 "encoding/base64" 6 "errors" 7 ) 8 9 func EntryptDesECB(data, key []byte) (string,error) { 10 if len(key) > 8 { 11 key = key[:8] 12 } 13 block, err := des.NewCipher(key) 14 if err != nil { 15 return "",err 16 } 17 bs := block.BlockSize() 18 data = PKCS5Padding(data, bs) 19 if len(data)%bs != 0 { 20 return "",errors.New("EntryptDesECB Need a multiple of the blocksize") 21 } 22 out := make([]byte, len(data)) 23 dst := out 24 for len(data) > 0 { 25 block.Encrypt(dst, data[:bs]) 26 data = data[bs:] 27 dst = dst[bs:] 28 } 29 return base64.StdEncoding.EncodeToString(out),nil 30 } 31 32 func EntryptDesECBByte(data, key []byte) ([]byte,error) { 33 if len(key) > 8 { 34 key = key[:8] 35 } 36 block, err := des.NewCipher(key) 37 if err != nil { 38 return nil,err 39 } 40 bs := block.BlockSize() 41 data = PKCS5Padding(data, bs) 42 if len(data)%bs != 0 { 43 return nil,errors.New("EntryptDesECB Need a multiple of the blocksize") 44 } 45 out := make([]byte, len(data)) 46 dst := out 47 for len(data) > 0 { 48 block.Encrypt(dst, data[:bs]) 49 data = data[bs:] 50 dst = dst[bs:] 51 } 52 buf := make([]byte, base64.StdEncoding.EncodedLen(len(out))) 53 base64.StdEncoding.Encode(buf, out) 54 return buf,nil 55 } 56 57 func DecryptDESECB(d string, key []byte) (string,error) { 58 data, err := base64.StdEncoding.DecodeString(d) 59 if err != nil { 60 return "",err 61 } 62 if len(key) > 8 { 63 key = key[:8] 64 } 65 block, err := des.NewCipher(key) 66 if err != nil { 67 return "",err 68 } 69 bs := block.BlockSize() 70 if len(data)%bs != 0 { 71 return "",errors.New("DecryptDES crypto/cipher: input not full blocks") 72 } 73 out := make([]byte, len(data)) 74 dst := out 75 for len(data) > 0 { 76 block.Decrypt(dst, data[:bs]) 77 data = data[bs:] 78 dst = dst[bs:] 79 } 80 out = PKCS5UnPadding(out) 81 return string(out),nil 82 } 83 84 func DecryptDESECBByte(d string, key []byte) ([]byte,error) { 85 data, err := base64.StdEncoding.DecodeString(d) 86 if err != nil { 87 return nil,err 88 } 89 if len(key) > 8 { 90 key = key[:8] 91 } 92 block, err := des.NewCipher(key) 93 if err != nil { 94 return nil,err 95 } 96 bs := block.BlockSize() 97 if len(data)%bs != 0 { 98 return nil,errors.New("DecryptDES crypto/cipher: input not full blocks") 99 } 100 out := make([]byte, len(data)) 101 dst := out 102 for len(data) > 0 { 103 block.Decrypt(dst, data[:bs]) 104 data = data[bs:] 105 dst = dst[bs:] 106 } 107 return PKCS5UnPadding(out),nil 108 }