AES加解密多版本(GO、JAVA、Python)实现

[TOC]

异构系统基于RESTful接口加解密

环境: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)
    // 去掉最后一个字节 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个字母和数字组成
     * 此处使用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模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    }

    // 解密
    @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库,下载地址https://pypi.python.org/pypi/pycrypto

# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES

AES_SECRET_KEY = 'B31F2A75FBF94099' #此处16|24|32个字符

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

    #加密函数
    def encrypt(self, text):

        cryptor = AES.new(self.key, self.mode,IV)
        self.ciphertext = cryptor.encrypt(pad(text))
        #AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码
        return base64.b64encode(self.ciphertext)

    #解密函数
    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

以上属于原创文章,转载请注明作者@怪咖
QQ:208275451
Email:[email protected]

你可能感兴趣的:(AES加解密多版本(GO、JAVA、Python)实现)