AES加解密多版本(GO、JAVA、Python)實現

怪咖_OOP發表於2018-02-03

[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

相關文章