终于实现了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. 【48.51%】【poj 1611】The Suspects

    Time Limit: 1000MS Memory Limit: 20000K Total Submissions: 34447 Accepted: 16711 Description Severe ...

  2. 【51.27%】【codeforces 604A】Uncowed Forces

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  3. ios开发网络学习:一:NSURLConnection发送GET,POST请求

    #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...

  4. python排序查找

    无序表查找 def seq_search(lst, key): found = False pos = 0 while pos < len(lst) and not found: if lst[ ...

  5. css3背景透明文字不透明

    在 FF/Chrome 等较新的浏览器中可以使用css属性background-color的rgba轻松实现背景透明,而文字保持不透明.而IE6/7/8浏览器不支持rgba,只有使用IE的专属滤镜fi ...

  6. 【u110】灾后重建

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] B地区在地震过后,所有村庄都造成了一定的损毁,而这场地震却没对公路造成什么影响.但是在村庄重建好之前, ...

  7. &quot;Swift&quot;编程语言

    来自英文文档.百度翻译以及自己没过4级的渣渣英语功底,为了自己以后看起来方便 About Swift 关于"海燕" IMPORTANT 重要 This is a prelimina ...

  8. Android 关于录音文件的编解码 实现米聊 微信一类的录音上传的功能

    最近老大要求做一个类米聊的app,于是就去找解决方案,首先用Android本身的MediaRecorder肯定是不行的,只支持amr,wav,acc,如果要做到Android,Iphone,pc通用的 ...

  9. 【b803】传纸条

    Time Limit: 1 second Memory Limit: 50 MB [问题描述] 小渊和小轩是好朋友也是同班同学,他们在一起总有谈不完的话题.一次素质拓展活动中,班上同学安排做成一个m行 ...

  10. [Javascript] Identify and Deal with NaN in JavaScript

    Dealing with the special NaN value can be tricky in JavaScript. It behaves like a number and not a n ...