TripleDES golang/python/ts 实现方式

1.TripleDES

TripleDES或3DES 是一种加密技术,通过应用数据加密标准(DES)算法的三次传递来增强数据的安全性,属于对称加密算法;

2. 实现方式

2.1. react-ts

function encrypt(text){
	import CryptoJS from 'crypto-js'
	const key = "qwertyuiopasdfghjklzxcvb"
	const text ="yuanli"
	const iv = "01234567"
	const result = CryptoJS.TripleDES.encrypt(text, CryptoJS.enc.Utf8.parse(key), {
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7,
		iv: CryptoJS.enc.Utf8.parse(iv)
	})
	return result
}

2.2.golang (test well)

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

func Encrypt(plain string) (string, error) {
	key := "qwertyuiopasdfghjklzxcvb"
	block, err := des.NewTripleDESCipher([]byte(key))
	if err != nil {
		return "", err
	}
	input := []byte(plain)
	input = PKCS5Padding(input, block.BlockSize())
	iv := "01234567"
	blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
	crypted := make([]byte, len(input))
	blockMode.CryptBlocks(crypted, input)
	return base64.StdEncoding.EncodeToString(crypted), err
}

func PKCS5Padding(input []byte, blockSize int) []byte {
	padding := blockSize - len(input)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(input, padText...)
}

func main() {
	s, err := Encrypt("yuanli")
	if err != nil {
		panic(err)
	}
	fmt.Println(s) # Z82teOQw6FE=
}

2.3. python

pip install pycryptodome
pip install Crypto
import base64

from Crypto.Cipher import DES3

class TripleDESEncryption():
    def __init__(self, key):
        self.key = key
        self.iv = b'01234567'
        self.length = DES3.block_size
        self.des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv)
        self.unpad = lambda date: date[0:-ord(date[-1])]

    def pad(self,text):
        count = len(text.encode('utf-8'))
        add = self.length - (count%self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, text):
        res = self.des3.encrypt(self.pad(text).encode('utf-8'))
        message = str(base64.b64encode(res), encoding="utf8")
        return message

if __name__ == '__main__':
    t = TripleDESEncryption("qwertyuiopasdfghjklzxcvb")
    e = t.encrypt("yuanli")
    print(e) # Z82teOQw6FE=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值