AES对称加密解密

golang加密

package main

import (
    "bytes"
    "crypto/aes"
    "encoding/hex"
    "fmt"
    "time"
)

func pKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

func EBCEncrypto(key, data []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    content := pKCS5Padding([]byte(data), block.BlockSize())
    crypted := make([]byte, len(content))

    if len(content)%block.BlockSize() != 0 {
        return nil, fmt.Errorf("crypto/cipher: input not full blocks")
    }

    src := content
    dst := crypted
    for len(src) > 0 {
        block.Encrypt(dst, src[:block.BlockSize()])
        src = src[block.BlockSize():]
        dst = dst[block.BlockSize():]
    }

    return crypted, nil
}

func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) {
    if len(sk) < 16 {
        return "", fmt.Errorf("error secrete key")
    }

    crypted, err := EBCEncrypto([]byte(sk[:16]), []byte(data))
    if err != nil {
        return "", err
    }

    return hex.EncodeToString(crypted), nil
}

func encryptAccountId(hexKey string, accountId string) string {
    tmStr := time.Now().UTC().Format("2006-01-02T15:04:05Z")
    content := accountId + "/" + tmStr
    src, _ := Aes128EncryptUseSecreteKey(hexKey, content)
    return src
}

func main() {
    fmt.Println(encryptAccountId("aaaabbbbccccdddd", "test333"))
    return
}

java加密解密

AesCryptoUtil.encrypt("test333", "aaaabbbbccccdddd");

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @Description AES 对称加密解密 Util 类
 */
@Slf4j
public class AesCryptoUtil {

    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_FULL = "AES/ECB/PKCS5Padding";
    private static final String CHARSET_NAME = "UTF-8";
    /**
     * 16 进制 chars
     */
    private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 对传入的 content 进行 AES 加密,返回 16 进制字符串
     *
     * @param content
     * @param hexKey
     * @return
     */
    public static String encrypt(String content, String hexKey) {
        try {
            // AES encrypt operation
            byte[] bytes = doAes(content.getBytes(CHARSET_NAME), hexKey, Cipher.ENCRYPT_MODE);
            // AES 加密后的字节数组转换为 16 进制字符串
            return bytes2HexStr(bytes);
        } catch (Exception e) {
            log.error("encrypt content failed", e);
            return null;
        }
    }

    /**
     * 对传入的 content 进行 AES 解密,返回字符串
     *
     * @param content
     * @param hexKey
     * @return
     */
    public static String decrypt(String content, String hexKey) {
        try {
            // AES decrypt operation
            byte[] bytes = doAes(hexStr2Bytes(content), hexKey, Cipher.DECRYPT_MODE);
            // AES 解密后的字节数组转换为字符串
            return new String(bytes, CHARSET_NAME);
        } catch (Exception e) {
            log.error("decrypt content failed", e);
            return null;
        }
    }

    /**
     * AES 对称加密解密 Operation
     *
     * @param contentBytes
     * @param hexKey
     * @param mode
     * @return
     */
    public static byte[] doAes(byte[] contentBytes, String hexKey, int mode) {
        try {
            // 生成 AES 密钥
            SecretKeySpec secretKeySpec = new SecretKeySpec(hexKey.getBytes(CHARSET_NAME), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_FULL);
            // init 密码器,加密(ENCRYPT_MODE)or 解密(DECRYPT_MODE)
            cipher.init(mode, secretKeySpec);
            return cipher.doFinal(contentBytes);
        } catch (Exception e) {
            log.error("do aes operation failed", e);
            return null;
        }
    }

    /**
     * byte[] to hex string
     * 1 byte = 2 hex
     *
     * @param bytes
     * @return
     */
    public static String bytes2HexStr(byte[] bytes) {
        if (bytes.length == 0) {
            return null;
        }
        char[] hexChars = new char[bytes.length << 1];
        int index = 0;
        for (byte b : bytes) {
            hexChars[index++] = HEX_CHARS[b >>> 4 & 0xf];
            hexChars[index++] = HEX_CHARS[b & 0xf];
        }
        return new String(hexChars);
    }

    /**
     * hex string to byte[]
     * 2 hex = 1 byte
     *
     * @param hexStr
     * @return
     */
    public static byte[] hexStr2Bytes(String hexStr) {
        if (StringUtils.isBlank(hexStr)) {
            return null;
        }
        byte[] bytes = new byte[hexStr.length() >> 1];
        for (int i = 0; i < bytes.length; i++) {
            String subStr = hexStr.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值