TripleDES golang/python/ts 实现方式

2. 实现方式

2.1. react-ts

js 复制代码
function encrypt(text){
	import CryptoJS from 'crypto-js'
	const key = "saxbj%2xas"
	const text ="liyuan"
	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)

c 复制代码
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

python 复制代码
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 = lamda 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
相关推荐
gc_229921 分钟前
学习Python中Selenium模块的基本用法(19:操作下拉框)
python·selenium
我的xiaodoujiao31 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 19--测试框架Pytest基础 3--前后置操作应用
python·学习·测试工具·pytest
std787935 分钟前
Rust 与 Go – 比较以及每个如何满足您的需求
开发语言·golang·rust
计算衎39 分钟前
基于Python实现CANoe和UDE交互通信工具实现,CAPL脚本通过python交互工具与UDE进行通信和调用UDE的组件获取UDE返回值。
python·capl·canoe·ude·nm_oncan
报错小能手40 分钟前
python(入门)map内置函数及import模块导入,as别名
开发语言·人工智能·python
梵得儿SHI1 小时前
Java 反射机制实战:对象属性复制与私有方法调用全解析
java·开发语言·java反射机制的实际应用·对象属性复制·反射调用私有方法·私有字段·类型兼容性和敏感字段忽略
sulikey1 小时前
C++的STL:深入理解 C++ 的 std::initializer_list
开发语言·c++·stl·list·initializerlist·c++标准库
liu****1 小时前
19.map和set的封装
开发语言·数据结构·c++·算法