[TOC]

Heterogeneous systems are encrypted and decrypted based on RESTful interfaces

Environment: GO1.8 / JDK1.8 / Python2.7

GO the sample

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)
	iferr ! = 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)
	iferr ! = nil {return "",err
	}
	block, err := aes.NewCipher(key)
	iferr ! = 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)
	returnappend(ciphertext, padtext...) } func PKCS5UnPadding(origData []byte) []byte {length := len(origData) // Remove the last byte unpadding := int(origData[length - 1])return origData[:(length - unpadding)]
}

Copy the code

Java example

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 { /** * The Key can contain 26 letters and digits. * The AES-128-CBC encryption mode is used, and the Key must be 16 bits. */ private static String sKey ="B31F2A75FBF94099";
    private static String ivParameter = "1234567890123456"; // Encryption @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()); Cipher. init(cipher. ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        returnnew BASE64Encoder().encode(encrypted); // BASE64 is used for transcoding. } // @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); Byte [] original = cipher.doFinal(encrypted1); String originalString = new String(original,"utf-8");
            return originalString;
        } catch (Exception ex) {
            returnnull; }}}Copy the code

The Python example

Rely on pycrypto library, download address: https://pypi.python.org/pypi/pycrypto

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

AES_SECRET_KEY = 'B31F2A75FBF94099' # 16 here 24 | | 32 characters

IV = "1234567890123456"

# padding algorithm
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

    # encrypt function
    def encrypt(self, text):

        cryptor = AES.new(self.key, self.mode,IV)
        self.ciphertext = cryptor.encrypt(pad(text))
        AES encoding is not necessarily ASCII character set. There may be problems when exporting to terminal or saving. Use Base64 encoding
        return base64.b64encode(self.ciphertext)

    # decryption function
    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 cryptography"
    e = aes_encrypt.encrypt(text)
    d = aes_encrypt.decrypt(e)
    print text
    print e
    print d
Copy the code

The above belong to the original article, reprint please indicate the author @ monster QQ:208275451