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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java AES256加密解密是一种常用的对称加密算法,它使用256位的密钥对数据进行加密和解密。下面是Java中使用AES256进行加密解密的基本步骤: 1. 导入相关的类库: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; ``` 2. 定义加密解密方法: ```java public class AESUtil { private static final String ALGORITHM = "AES"; private static final TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static String encrypt(String data, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 3. 使用加密解密方法: ```java public class Main { public static void main(String[] args) { try { String data = "Hello, World!"; String key = "0123456789abcdef0123456789abcdef"; // 256位密钥 String encryptedData = AESUtil.encrypt(data, key); System.out.println("加密后的数据:" + encryptedData); String decryptedData = AESUtil.decrypt(encryptedData, key); System.out.println("解密后的数据:" + decryptedData); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了如何使用Java进行AES256加密解密。需要注意的是,密钥的长度必须是256位(32字节),并且在实际应用中应该使用安全的方式来保存和传输密钥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值