golang实现3DES加解密

3DES加解密,本文选择了CBC加解密模式。

import (
    "crypto/des"
    "bytes"
    "crypto/cipher"
)
//3DES——CBC模式,key长度必须为24,加密解密key和向量需要互相匹配
func TripleDesEncrypt(origData,key,iv []byte) ([]byte, error) {

    //iv即是向量,长度为8
    block, err := des.NewTripleDESCipher(key)
    if err != nil {
         return nil, err
        }
    origData = PKCS5Padding(origData, block.BlockSize())
    blockMode := cipher.NewCBCEncrypter(block, iv)
    crypted := make([]byte, len(origData))
    blockMode.CryptBlocks(crypted, origData)
    return crypted, nil
 }
// 3DES解密
func TripleDesDecrypt(crypted, key,iv []byte) ([]byte, error) {
    block, err := des.NewTripleDESCipher(key)
    if err != nil {
          return nil, err
         }
    blockMode := cipher.NewCBCDecrypter(block, iv)
    origData := make([]byte, len(crypted))
    blockMode.CryptBlocks(origData, crypted)
    origData = PKCS5UnPadding(origData)
    return origData, nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
    length := len(origData)
    // 去掉最后一个字节 unpadding 次
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

发布了8 篇原创文章 · 获赞 1 · 访问量 9103

猜你喜欢

转载自blog.csdn.net/xiaoxiao_haiyan/article/details/81320350