密码学-3DES

3DES加密算法

3DES加密算法的使用与DES的用法基本相同,使用方法如下:

    package main

    import (
        "bytes"
        "crypto/des"
        "crypto/cipher"
        "fmt"
        "encoding/base64"
    )

    //补码
    func PKCS5Padding(ciphertext []byte, blocksize int) []byte {
        padding := blocksize - len(ciphertext)%blocksize
        padtext := bytes.Repeat([]byte{byte(padding)}, padding)
        return append(ciphertext, padtext...)
    }

    //3DES加密
    func TripleDescrypt(origData []byte, key []byte) []byte {
        //3DES的秘钥长度必须为24位
        block, _ := des.NewTripleDESCipher(key)
        //补码
        origData = PKCS5Padding(origData, block.BlockSize())
        //设置加密模式
        blockMode := cipher.NewCBCEncrypter(block, key[:8])
        //创建密文数组,加密
        crypted := make([]byte, len(origData))
        blockMode.CryptBlocks(crypted, origData)
        return crypted
    }

    //解密
    func TipleDesDecrypt(crypted, key []byte) [] byte {
        block, _ := des.NewTripleDESCipher(key)
        blockMode := cipher.NewCBCDecrypter(block, key[:8])
        origData := make([]byte, len(crypted))
        blockMode.CryptBlocks(origData, crypted)
        origData = PKCS5UnPadding(origData)
        return origData
    }

    //去码
    func PKCS5UnPadding(origData []byte) []byte {
        length := len(origData)
        // 去掉最后一个字节 unpadding 次
        unpadding := int(origData[length-1])
        return origData[:(length - unpadding)]
    }
    func main() {
        //长度为24byte
        key := []byte("123456789012345678901234")
        a := base64.StdEncoding.EncodeToString(TripleDescrypt([]byte("hello world"), key))
        //加密
        fmt.Println(a)


    }

猜你喜欢

转载自blog.csdn.net/qq_37133717/article/details/80356248