因为项目的需要用到golang的一种特殊的加密解密算法AES/ECB/PKCS5,但是算法并没有包含在标准库中,经过多次失败的尝试,终于解码成功,特此分享:

/*
描述 : golang AES/ECB/PKCS5 加密解密
date : 2016-04-08
*/ package main import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
"strings"
) func main() {
/*
*src 要加密的字符串
*key 用来加密的密钥 密钥长度可以是128bit、192bit、256bit中的任意一个
*16位key对应128bit
*/
src := "0.56"
key := "0123456789abcdef" crypted := AesEncrypt(src, key)
AesDecrypt(crypted, []byte(key))
Base64URLDecode("39W7dWTd_SBOCM8UbnG6qA")
} func Base64URLDecode(data string) ([]byte, error) {
var missing = (4 - len(data)%4) % 4
data += strings.Repeat("=", missing)
res, err := base64.URLEncoding.DecodeString(data)
fmt.Println(" decodebase64urlsafe is :", string(res), err)
return base64.URLEncoding.DecodeString(data)
} func Base64UrlSafeEncode(source []byte) string {
// Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed.
bytearr := base64.StdEncoding.EncodeToString(source)
safeurl := strings.Replace(string(bytearr), "/", "_", -1)
safeurl = strings.Replace(safeurl, "+", "-", -1)
safeurl = strings.Replace(safeurl, "=", "", -1)
return safeurl
} func AesDecrypt(crypted, key []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("err is:", err)
}
blockMode := NewECBDecrypter(block)
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
fmt.Println("source is :", origData, string(origData))
return origData
} func AesEncrypt(src, key string) []byte {
block, err := aes.NewCipher([]byte(key))
if err != nil {
fmt.Println("key error1", err)
}
if src == "" {
fmt.Println("plain content empty")
}
ecb := NewECBEncrypter(block)
content := []byte(src)
content = PKCS5Padding(content, block.BlockSize())
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
// 普通base64编码加密 区别于urlsafe base64
fmt.Println("base64 result:", base64.StdEncoding.EncodeToString(crypted)) fmt.Println("base64UrlSafe result:", Base64UrlSafeEncode(crypted))
return crypted
} func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
} func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
} type ecb struct {
b cipher.Block
blockSize int
} func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
} type ecbEncrypter ecb // NewECBEncrypter returns a BlockMode which encrypts in electronic code book
// mode, using the given Block.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(b))
}
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
} type ecbDecrypter ecb // NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}

这是作者对多篇博客和代码整理而成,如果您觉得本文对您有帮助,欢迎打赏一杯咖啡作为对作者的鼓励,谢谢!

鸣谢:

Go加密解密之AES:http://blog.studygolang.com/tag/aes_encrypt/

yinheli: https://gist.github.com/yinheli/3370e0e901329b639be4

golang AES/ECB/PKCS5 加密解密 url-safe-base64的更多相关文章

  1. C#调用Crypto++库AES ECB CBC加解密

    本文章使用上一篇<C#调用C++类库例子>的项目代码作为Demo.本文中,C#将调用C++的Crypto++库,实现AES的ECB和CBC加解密. 一.下载Crypto 1.进入Crypt ...

  2. python 实现 AES ECB模式加解密

    AES ECB模式加解密使用cryptopp完成AES的ECB模式进行加解密. AES加密数据块分组长度必须为128比特,密钥长度可以是128比特.192比特.256比特中的任意一个.(8比特 == ...

  3. 微信小程序aes前后端加密解密交互

    aes前后端加密解密交互 小程序端 1. 首先引入aes.js /** * [description] CryptoJS v3.1.2 * [description] zhuangzhudada so ...

  4. AES ECB PKCS5/PKCS7 加解密 python实现 支持中文

    目录 ECB模式介绍 pkcs5padding和pkcs7padding的区别 python实现 注意事项 ECB模式介绍 电码本模式(Electronic Codebook Book (ECB) 这 ...

  5. Android DES加密的CBC模式加密解密和ECB模式加密解密

    DES加密共有四种模式:电子密码本模式(ECB).加密分组链接模式(CBC).加密反馈模式(CFB)和输出反馈模式(OFB). CBC模式加密: import java.security.Key; i ...

  6. Java使用AES算法进行加密解密

    一.加密 /** * 加密 * @param src 源数据字节数组 * @param key 密钥字节数组 * @return 加密后的字节数组 */ public static byte[] En ...

  7. AES不同语言加密解密

    AES加密模式和填充方式:还有其他 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度 AES/CBC/NoPadding 16 不支持 AES/CBC/PKCS5Padding 32 ...

  8. AES字节数组加密解密流程

    AES类时微软MSDN中最常用的加密类,微软官网也有例子,参考链接:https://docs.microsoft.com/zh-cn/dotnet/api/system.security.crypto ...

  9. 自己写的AES和RSA加密解密工具

    package com.sdyy.common.utils; import java.security.Key; import java.security.KeyFactory; import jav ...

随机推荐

  1. XCOJ 1102 (树形DP+背包)

    题目链接: http://xcacm.hfut.edu.cn/oj/problem.php?id=1102 题目大意:树上取点.父亲出现了,其儿子包括孙子...都不能出现.给定预算,问最大值. 解题思 ...

  2. JavaScript,一个超级简单的方法判断浏览器的内核前缀

    先说明,此处的方法是说超级简单的方法,不是指代码超级少,而是用非常简单的知识点,只要懂得怎么写JavaScript的行内样式就可以判断. 大家应该还记得JavaScript行内样式怎么写吧?(看来我是 ...

  3. 达成成就:排名和AC数相同

    233333 纪念一下.(268会不会是幸运数字呢0.0

  4. 【wikioi】1553 互斥的数(hash+set)

    http://wikioi.com/problem/1553/ 一开始我也知道用set来判a[i]/p是否在集合中,在的话就直接删掉. 但是我没有想到要排序,也没有想到当存在a,b使得a/p==b时到 ...

  5. 彻底卸载oracle数据库

    有时候因为各种各样的原因,我们不得不重装Oracle,但按照一般的操作,很多朋友用了oracle的删除,然后,你会发现重新安装时,点了下一步安装界面就消失了.事实证明,万能的重启也是解决不了问题的.往 ...

  6. MySQL 用户管理——权限表

    权限表 权限表存放在mysql数据库中 user表结构 用户列:Host.User.Password 权限列:*priv 资源控制列:max* 安全列:其余   db表 存储了用户对某个数据库的操作权 ...

  7. 在openGL中绘制图形

    点的绘制.: glVertex*():星号表示函数要有后缀 该函数 需要放在glBegin函数和glEnd函数之间,glBegin函数的向量指定绘制图元的类型,而glEnd函数没有参数,例如: glB ...

  8. Css - 基础的css阴影效果

    基本的css3阴影效果 width:971px; height:608px; border:1px solid #ccc; background-color:#fff; filter:progid:D ...

  9. [转]常用 Git 命令清单

    作者: 阮一峰 我每天使用 Git ,但是很多命令记不住. 一般来说,日常使用只要记住下图6个命令,就可以了.但是熟练使用,恐怕要记住60-100个命令. 下面是我整理的常用 Git 命令清单.几个专 ...

  10. 动态样式语言Less学习笔记

    介绍资料参见:http://www.bootcss.com/p/lesscss/ LESS 将 CSS 赋予了动态语言的特性,如 变量, 继承,运算, 函数. LESS 既可以在 客户端 上运行 (支 ...