go与java互用的AES实现
终于实现了go与java互用的AES算法实现。基于go可以编译windows与linux下的命令行工具,十分方便。
- Java源码
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static byte[] encrypt(String key, byte[] origData) throws GeneralSecurityException {
byte[] keyBytes = getKeyBytes(key);
byte[] buf = new byte[16];
System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes));
return cipher.doFinal(origData);
}
public static byte[] decrypt(String key, byte[] crypted) throws GeneralSecurityException {
byte[] keyBytes = getKeyBytes(key);
byte[] buf = new byte[16];
System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes));
return cipher.doFinal(crypted);
}
private static byte[] getKeyBytes(String key) {
byte[] bytes = key.getBytes();
return bytes.length == 16 ? bytes : Arrays.copyOf(bytes, 16);
}
public static String encrypt(String key, String val) throws GeneralSecurityException {
byte[] origData = val.getBytes();
byte[] crypted = encrypt(key, origData);
return Base64.Encoder.RFC4648_URLSAFE.encodeToString(crypted);
}
public static String decrypt(String key, String val) throws GeneralSecurityException {
byte[] crypted = Base64.Decoder.RFC4648_URLSAFE.decode(val);
byte[] origData = decrypt(key, crypted);
return new String(origData);
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.print("Usage: java AES (-e|-d) <key> <content>");
}
if ("-e".equals(args[0])) {
System.out.println(encrypt(args[1], args[2]));
} else if ("-d".equals(args[0])) {
System.out.println(decrypt(args[1], args[2]));
} else {
System.err.print("Usage: java AES (-e|-d) <key> <content>");
}
}
}
- Go源码
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"os"
)
func getKeyBytes(key string) []byte {
keyBytes := []byte(key)
switch l := len(keyBytes); {
case l < 16:
keyBytes = append(keyBytes, make([]byte, 16-l)...)
case l > 16:
keyBytes = keyBytes[:16]
}
return keyBytes
}
func encrypt(key string, origData []byte) ([]byte, error) {
keyBytes := getKeyBytes(key)
block, err := aes.NewCipher(keyBytes)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, keyBytes[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func decrpt(key string, crypted []byte) ([]byte, error) {
keyBytes := getKeyBytes(key)
block, err := aes.NewCipher(keyBytes)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, keyBytes[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}
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 := int(origData[length-1])
return origData[:(length - unpadding)]
}
func Encrypt(key string, val string) (string, error) {
origData := []byte(val)
crypted, err := encrypt(key, origData)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(crypted), nil
}
func Decrypt(key string, val string) (string, error) {
crypted, err := base64.URLEncoding.DecodeString(val)
if err != nil {
return "", err
}
origData, err := decrpt(key, crypted)
if err != nil {
return "", err
}
return string(origData), nil
}
func main() {
argc := len(os.Args)
if argc != 4 {
os.Stdout.WriteString("usage: AES (-e|-d) <key> <content>")
return
}
switch os.Args[1] {
case "-e":
ret, err := Encrypt(os.Args[2], os.Args[3])
if err != nil {
os.Stderr.WriteString(err.Error())
os.Exit(1)
}
println(ret)
case "-d":
ret, err := Decrypt(os.Args[2], os.Args[3])
if err != nil {
os.Stderr.WriteString(err.Error())
os.Exit(1)
}
println(ret)
default:
os.Stdout.WriteString("usage: AES (-e|-d) <key> <content>")
}
}
使用go可以编译Windows与Linux下的可执行工具。
go与java互用的AES实现的更多相关文章
- Delphi与JAVA互加解密AES算法
搞了半天终于把这个对应的参数搞上了,话不多说,先干上代码: package com.bss.util; import java.io.UnsupportedEncodingException; imp ...
- java对称加密(AES)
java对称加密(AES) 博客分类: Java javaAES对称加密 /** * AESHelper.java * cn.com.songjy.test * * Function: TODO * ...
- Java 环境下使用 AES 加密的特殊问题处理
在 Java 环境下使用 AES 加密,在密钥长度和字节填充方面有一些比较特殊的处理. 1. 密钥长度问题 默认 Java 中仅支持 128 位密钥,当使用 256 位密钥的时候,会报告密钥长度错误 ...
- Java利用DES/3DES/AES这三种算法分别实现对称加密
转载地址:http://blog.csdn.net/smartbetter/article/details/54017759 有两句话是这么说的: 1)算法和数据结构就是编程的一个重要部分,你若失掉了 ...
- JAVA和PYTHON同时实现AES的加密解密操作---且生成的BASE62编码一致
终于有机会生产JAVA的东东了. 有点兴奋. 花了一天搞完.. java(关键key及算法有缩减): package com.security; import javax.crypto.Cipher; ...
- android开发 java与c# 兼容AES加密
由于android客户端采用的是AES加密,服务器用的是asp.net(c#),所以就造成了不一致的加密与解密问题,下面就贴出代码,已经试验过. using System; using System. ...
- C#对接JAVA系统遇到的AES加密坑
起因对接合作伙伴的系统,需要对数据进行AES加密 默认的使用了已经写好的帮助类中加密算法,发现结果不对,各种尝试改变加密模式改变向量等等折腾快一下午.最后网上查了下AES在JAVA里面的实现完整代码如 ...
- JAVA 加密算法初探DES&AES
开发项目中需要将重要数据缓存在本地以便在离线是读取,如果不对数据进行处理,很容易造成损失.所以,我们一般对此类数据进行加密处理.这里,主要介绍两种简单的加密算法:DES&AES. 先简单介绍一 ...
- JAVA的对称加密算法AES——加密和解密
出自: http://blog.csdn.net/hongtashan11/article/details/6599645 http://www.cnblogs.com/liunanjava/p/42 ...
随机推荐
- 【2016 Summary】为过往补课、为将来夯实
前言 看了CSDN上非常多"我的2016"年终总结,也就不能免俗地来写一波.按着时间轴捋一捋这过去一年的经过,也算是这元旦假期总一个午后的休闲时光了.(结果没想到的是午饭前開始写的 ...
- 小强的HTML5移动开发之路(48)——(小练习)新闻订阅系统【1】
一.总体设计 二.数据库设计 --新闻类别表 create table news_cate( news_cateid int primary key auto_increment, news_icon ...
- [Javascript] Javascript 'in' opreator
If you want to check whether a key is inside an Object or Array, you can use 'in': Object: const obj ...
- springMVC返回json数据乱码问题及@RequestMapping 详解
原文地址:https://blog.csdn.net/u010127245/article/details/51774074 一.@RequestMapping RequestMapping是一个用来 ...
- AE属性表操作
转自chanyinhelv原文AE属性表操作 实现的操作包括:1.打开属性表:2.编辑属性表:3.增加属性列:4.数据排序:5.字段计算…… 嗯,实现的功能目前就这些吧,后续还会继续跟进,还望大家多多 ...
- dom对象常用的属性和方法有哪些?
dom对象常用的属性和方法有哪些? 一.总结 一句话总结: 1.document属性和方法:document的属性有head,body之类,方法有各种获取element的方法 2.element的属性 ...
- JQuery:cookie插件
JQuery居然没有操作cookie相关的函数,搜了下官方有个cookie的插件. 简单使用方法: <head> <title>JQuery-Cookie插件</titl ...
- sparksql json 合并json数据
java public class Demo { private static SparkConf conf = new SparkConf().setAppName("demo" ...
- word 论文排版 —— 按指定格式章节的自动编号
在word中如何实现章节标题自动编号 标题样式与标题的编号是两个步骤,为标题建立编号是在为标题样式确定的基础后进行的.这是显而易见的,也即只有先定义了多级标题(也可使用 word 自带的标题样式),才 ...
- FileReader采用的默认编码
很久以前听教学视频,里面讲到Java采用的默认编码是ISO-8859-1,一直记着. 但是最近重新看IO流的时候,惊讶地发现,在不指定字符编码的情况下,FileReader居然可以读取内容为中文的文本 ...