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
相关推荐
学习编程的gas9 分钟前
C++面向对象编程入门:从类与对象说起(一)
开发语言·c++
冼紫菜10 分钟前
【Spring Boot 多模块项目】@MapperScan失效、MapperScannerConfigurer 报错终极解决方案
java·开发语言·mybatis
Bear on Toilet42 分钟前
Bug日记——实现“日期类”
开发语言·c++·bug
apcipot_rain1 小时前
《面向对象程序设计-C++》实验五 虚函数的使用及抽象类
开发语言·c++
小彭律师2 小时前
数字化工厂中央控制室驾驶舱系统架构文档
python
明月看潮生3 小时前
青少年编程与数学 02-019 Rust 编程基础 05课题、复合数据类型
开发语言·青少年编程·rust·编程与数学
幼稚诠释青春3 小时前
Java学习笔记(对象)
java·开发语言
你怎么知道我是队长3 小时前
Go语言标识符
后端·golang
old_power4 小时前
【Python】PDF文件处理(PyPDF2、borb、fitz)
python·pdf
测试开发Kevin4 小时前
从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架
python·pytest