golang - DES加密ECB(模式)

Java默认DES算法使用DES/ECB/PKCS5Padding,而golang认为这种方式是不安全的,所以故意没有提供这种加密方式,那如果我们还是要用到怎么办?下面贴上golang版的DES ECB加密解密代码(默认对密文做了base64处理)。

1package main 2 3import ( 4 log "ad-service/alog" 5 "bytes" 6 "crypto/des" 7 "encoding/base64" ) 8 9func EntryptDesECB(data, key []byte) string { if len(key) > 8 { 10 key = key[:8] 11 } 12 block, err := des.NewCipher(key) if err != nil { 13 log.Errorf("EntryptDesECB newCipher error[%v]", err) return "" } 14 bs := block.BlockSize() 15 data = PKCS5Padding(data, bs) if len(data)%bs != 0 { 16 log.Error("EntryptDesECB Need a multiple of the blocksize") return "" } out := make([]byte, len(data)) 17 dst := out 18 for len(data) > 0 { 19 block.Encrypt(dst, data[:bs]) 20 data = data[bs:] 21 dst = dst[bs:] 22 } return base64.StdEncoding.EncodeToString(out) 23} 24func DecryptDESECB(d, key []byte) string { 25 data, err := base64.StdEncoding.DecodeString(d) if err != nil { 26 log.Errorf("DecryptDES Decode base64 error[%v]", err) return "" } if len(key) > 8 { 27 key = key[:8] 28 } 29 block, err := des.NewCipher(key) if err != nil { 30 log.Errorf("DecryptDES NewCipher error[%v]", err) return "" } 31 bs := block.BlockSize() if len(data)%bs != 0 { 32 log.Error("DecryptDES crypto/cipher: input not full blocks") return "" } out := make([]byte, len(data)) 33 dst := out 34 for len(data) > 0 { 35 block.Decrypt(dst, data[:bs]) 36 data = data[bs:] 37 dst = dst[bs:] 38 } out = PKCS5UnPadding(out) return string(out) 39} 40 41func PKCS5Padding(ciphertext []byte, blockSize int) []byte { 42 padding := blockSize - len(ciphertext)%blockSize 43 padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) 44} 45 46func PKCS5UnPadding(origData []byte) []byte { 47 length := len(origData) 48 unpadding := int(origData[length-1]) return origData[:(length - unpadding)] 49}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Twitter的分布式自增ID算法snowflake (Java版)

概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移