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
相关推荐
老蒋每日coding3 小时前
LangGraph:从入门到Multi-Agent超级智能体系统进阶开发
开发语言·python
郁闷的网纹蟒3 小时前
虚幻5---第12部分---蒙太奇
开发语言·c++·ue5·游戏引擎·虚幻
岚天start3 小时前
Python HTTP服务器添加简单用户名密码认证的三种方案
服务器·python·http
小旭95273 小时前
Java 反射详解
java·开发语言·jvm·面试·intellij-idea
雨季6663 小时前
Flutter 三端应用实战:OpenHarmony “极简文本行数统计器”
开发语言·前端·flutter·ui·交互
cuber膜拜3 小时前
Weaviate 简介与基本使用
数据库·python·docker·向量数据库·weaviate
m0_748233173 小时前
PHP版本演进:从7.x到8.x全解析
java·开发语言·php
HealthScience3 小时前
DNA具体怎么转为蛋白质的?
python
雨季6664 小时前
Flutter 三端应用实战:OpenHarmony 简易“动态字体大小调节器”交互模式深度解析
开发语言·flutter·ui·交互·dart
zhengfei6114 小时前
精选的优秀法证分析工具和资源列表
开发语言·php