github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/bdcrypto/3des.go (about) 1 package bdcrypto 2 3 import ( 4 "crypto/cipher" 5 "crypto/des" 6 "errors" 7 ) 8 9 // DESCBCEncrypt3 实现3DES加密, CBC模式 10 func DESCBCEncrypt3(plaintext, key, iv []byte) (ciphertext []byte, err error) { 11 block, err := des.NewTripleDESCipher(key) 12 if err != nil { 13 return nil, err 14 } 15 16 defer func() { 17 if rerr := recover(); rerr != nil { 18 err = errors.New(rerr.(string)) 19 } 20 }() 21 22 bs := block.BlockSize() 23 plaintext = PKCS5Padding(plaintext, bs) 24 blockMode := cipher.NewCBCEncrypter(block, iv) 25 26 ciphertext = make([]byte, len(plaintext)) 27 blockMode.CryptBlocks(ciphertext, plaintext) 28 return ciphertext, nil 29 } 30 31 // DESCBCDecrypt3 实现3DES解密, CBC模式 32 func DESCBCDecrypt3(ciphertext, key, iv []byte) (plaintext []byte, err error) { 33 block, err := des.NewTripleDESCipher(key) 34 if err != nil { 35 return nil, err 36 } 37 38 defer func() { 39 if rerr := recover(); rerr != nil { 40 err = errors.New(rerr.(string)) 41 } 42 }() 43 44 blockMode := cipher.NewCBCDecrypter(block, iv) 45 46 plaintext = make([]byte, len(ciphertext)) 47 blockMode.CryptBlocks(plaintext, ciphertext) 48 plaintext = PKCS5UnPadding(plaintext) 49 return plaintext, nil 50 }