终于实现了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实现的更多相关文章

  1. Delphi与JAVA互加解密AES算法

    搞了半天终于把这个对应的参数搞上了,话不多说,先干上代码: package com.bss.util; import java.io.UnsupportedEncodingException; imp ...

  2. java对称加密(AES)

    java对称加密(AES) 博客分类: Java javaAES对称加密  /** * AESHelper.java * cn.com.songjy.test * * Function: TODO * ...

  3. Java 环境下使用 AES 加密的特殊问题处理

    在 Java 环境下使用 AES 加密,在密钥长度和字节填充方面有一些比较特殊的处理. 1. 密钥长度问题 默认 Java 中仅支持 128 位密钥,当使用 256 位密钥的时候,会报告密钥长度错误 ...

  4. Java利用DES/3DES/AES这三种算法分别实现对称加密

    转载地址:http://blog.csdn.net/smartbetter/article/details/54017759 有两句话是这么说的: 1)算法和数据结构就是编程的一个重要部分,你若失掉了 ...

  5. JAVA和PYTHON同时实现AES的加密解密操作---且生成的BASE62编码一致

    终于有机会生产JAVA的东东了. 有点兴奋. 花了一天搞完.. java(关键key及算法有缩减): package com.security; import javax.crypto.Cipher; ...

  6. android开发 java与c# 兼容AES加密

    由于android客户端采用的是AES加密,服务器用的是asp.net(c#),所以就造成了不一致的加密与解密问题,下面就贴出代码,已经试验过. using System; using System. ...

  7. C#对接JAVA系统遇到的AES加密坑

    起因对接合作伙伴的系统,需要对数据进行AES加密 默认的使用了已经写好的帮助类中加密算法,发现结果不对,各种尝试改变加密模式改变向量等等折腾快一下午.最后网上查了下AES在JAVA里面的实现完整代码如 ...

  8. JAVA 加密算法初探DES&AES

    开发项目中需要将重要数据缓存在本地以便在离线是读取,如果不对数据进行处理,很容易造成损失.所以,我们一般对此类数据进行加密处理.这里,主要介绍两种简单的加密算法:DES&AES. 先简单介绍一 ...

  9. JAVA的对称加密算法AES——加密和解密

    出自: http://blog.csdn.net/hongtashan11/article/details/6599645 http://www.cnblogs.com/liunanjava/p/42 ...

随机推荐

  1. [Angular] Create custom validators for formControl and formGroup

    Creating custom validators is easy, just create a class inject AbstractControl. Here is the form we ...

  2. Android中动态设置GridView的列数、列宽和行高

    在使用GridView时我们知道,列数是可以通过设计时的属性来设置的,列的宽度则是根据列数和GridView的宽度计算出来的.但是有些时候我们想实现列数是动态改变的效果,即列的宽度保持某个值,列的数量 ...

  3. Dynamips GNS3

    https://baike.baidu.com/item/dynamips Dynamips的原始名称为Cisco 7200 Simulator,源于Christophe Fillot在2005年8月 ...

  4. Ajax基础与Json应用(一)

    一.Ajax概念 Ajax是异步的javacript和xml 发音: Ajax [ˈeɪˌdʒæks] 二.同步与异步 传统方式(同步):一个请求对应一个回应,他们是同步的,回应不完成,没办法对这个页 ...

  5. dbvisualizer 使用笔记

    快捷键:CTRL+SHIFT+F  格式化选中的sql语句 导入导出数据操作 导入: 1.将Exel文件另存为csv文件 2.在dbvisualizer中点击开发数据库,如test_dev,然后在te ...

  6. EXTJS和javaweb应用的开发思路

    近期.做些几个基于extjs界面的应用.在此.总结一下要点.标题是基于javaweb,可是基本上各种server端语言都适用.使用Extjs做界面,无非就是取消了原来非常多的jsp文件,转而使用Ext ...

  7. 【9309】求Y=X1/3

    Time Limit: 1 second Memory Limit: 2 MB 问题描述 求Y=X1/3次方的值.X由键盘输入(x不等于0,在整型范围内).利用下列迭代公式计算: yn + 1=2/3 ...

  8. java-线程-生产者-消费者

    概述 在Java中有四种方法支持同步,其中前三个是同步方法,一个是管道方法. wait() / notify()方法 await() / signal()方法 BlockingQueue阻塞队列方法 ...

  9. 【最大M子段和】dp + 滚动数组

    题目描述 给定 n 个数求这 n 个数划分成互不相交的 m 段的最大 m 子段和. 给出一段整数序列 A1,A2,A3,A4,...,Ax,...,An ,其中 1≤x≤n≤1,000,000, -3 ...

  10. IOS开源项目指标

    https://github.com/edagarli/open-ios-projects/blob/master/README.md 版权声明:本文博主原创文章,博客,未经同意不得转载.