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
相关推荐
Villiam_AY1 小时前
Redis 缓存机制详解:原理、问题与最佳实践
开发语言·redis·后端
UQWRJ2 小时前
菜鸟教程R语言一二章阅读笔记
开发语言·笔记·r语言
岁忧3 小时前
macOS配置 GO语言环境
开发语言·macos·golang
朝朝又沐沐4 小时前
算法竞赛阶段二-数据结构(36)数据结构双向链表模拟实现
开发语言·数据结构·c++·算法·链表
毛飞龙4 小时前
Python类(class)参数self的理解
python··self
魔尔助理顾问4 小时前
系统整理Python的循环语句和常用方法
开发语言·后端·python
Ares-Wang4 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
遇见尚硅谷5 小时前
C语言:*p++与p++有何区别
c语言·开发语言·笔记·学习·算法
SkyrimCitadelValinor5 小时前
c#中让图片显示清晰
开发语言·c#
艾莉丝努力练剑6 小时前
【数据结构与算法】数据结构初阶:详解排序(二)——交换排序中的快速排序
c语言·开发语言·数据结构·学习·算法·链表·排序算法