[TOC]
異構(gòu)系統(tǒng)基于RESTful接口加解密
環(huán)境:GO1.8/JDK1.8/Python2.7
GO示例
package common
import (
"crypto/aes"
"crypto/cipher"
"bytes"
"fmt"
"encoding/base64"
)
var key = []byte("B31F2A75FBF94099")
var iv = []byte("1234567890123456")
type AES_CBC struct {
}
func Encrypt(origData []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
// origData = ZeroPadding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return base64.StdEncoding.EncodeToString(crypted), nil
}
func Decrypt(crypted string) (string, error) {
decodeData,err:=base64.StdEncoding.DecodeString(crypted)
if err != nil {
return "",err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
//blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(decodeData))
blockMode.CryptBlocks(origData, decodeData)
origData = PKCS5UnPadding(origData)
// origData = ZeroUnPadding(origData)
return string(origData), nil
}
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext) % blockSize
padtext := bytes.Repeat([]byte{0}, padding)
return append(ciphertext, padtext...)
}
func ZeroUnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length - 1])
return origData[:(length - unpadding)]
}
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)
// 去掉最后一個(gè)字節(jié) unpadding 次
unpadding := int(origData[length - 1])
return origData[:(length - unpadding)]
}
Java示例
package com.yz.common.security.aes;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author yangzhao
* @Description
* @Date create by 15:49 18/2/3
*/
public class AES_CBC implements AES {
/**
* 加密用的Key 可以用26個(gè)字母和數(shù)字組成
* 此處使用AES-128-CBC加密模式男图,key需要為16位檀训。
*/
private static String sKey = "B31F2A75FBF94099";
private static String ivParameter = "1234567890123456";
// 加密
@Override
public String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式柑潦,需要一個(gè)向量iv,可增加加密算法的強(qiáng)度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);//此處使用BASE64做轉(zhuǎn)碼峻凫。
}
// 解密
@Override
public String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
}
}
Python示例
依賴pycrypto庫(kù)渗鬼,下載地址https://pypi.python.org/pypi/pycrypto
# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
AES_SECRET_KEY = 'B31F2A75FBF94099' #此處16|24|32個(gè)字符
IV = "1234567890123456"
# padding算法
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
class AES_ENCRYPT(object):
def __init__(self):
self.key = AES_SECRET_KEY
self.mode = AES.MODE_CBC
#加密函數(shù)
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode,IV)
self.ciphertext = cryptor.encrypt(pad(text))
#AES加密時(shí)候得到的字符串不一定是ascii字符集的,輸出到終端或者保存時(shí)候可能存在問題荧琼,使用base64編碼
return base64.b64encode(self.ciphertext)
#解密函數(shù)
def decrypt(self, text):
decode = base64.b64decode(text)
cryptor = AES.new(self.key, self.mode,IV)
plain_text = cryptor.decrypt(decode)
return plain_text
if __name__ == '__main__':
aes_encrypt = AES_ENCRYPT()
text = "python 加密"
e = aes_encrypt.encrypt(text)
d = aes_encrypt.decrypt(e)
print text
print e
print d
以上屬于原創(chuàng)文章譬胎,轉(zhuǎn)載請(qǐng)注明作者@怪咖
QQ:208275451
Email:yangzhao_java@163.com