java实现标准AES加密算法

package FindTool.AES;

import Public.Myfile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Random;

/**
 * <h1>AES 加密和解密示例代码</h1>
 * Created by woniu
 * */
public class AESExample {

    /** 加密模式之 ECB,算法/模式/补码方式 */
    private static final String AES_ECB = "AES/ECB/PKCS5Padding";

    /** 加密模式之 CBC,算法/模式/补码方式 */
    private static final String AES_CBC = "AES/CBC/PKCS5Padding";

    /** 加密模式之 CFB,算法/模式/补码方式 */
    private static final String AES_CFB = "AES/CFB/PKCS5Padding";

    /** AES 中的 IV 必须是 16 字节(128位)长 */
    private static final Integer IV_LENGTH = 16;

    /***
     * <h2>空校验</h2>
     * @param str 需要判断的值
     */
    public static boolean isEmpty(Object str) {
        return null == str || "".equals(str);
    }

    /***
     * <h2>String 转 byte</h2>
     * @param str 需要转换的字符串
     */
    public static byte[] getBytes(String str){
        if (isEmpty(str)) {
            return null;
        }

        try {
            return str.getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /***
     * <h2>初始化向量(IV),它是一个随机生成的字节数组,用于增加加密和解密的安全性</h2>
     */
    public static String getIV(){
        String str = "a04w5ER9gJ604y6Q8N0cMt0i8FsSFz4C";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < IV_LENGTH ; i++){
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /***
     * <h2>获取一个 AES 密钥规范</h2>
     */
    public static SecretKeySpec getSecretKeySpec(String key){
        SecretKeySpec secretKeySpec = new SecretKeySpec(getBytes(key), "AES");
        return secretKeySpec;
    }

    /**
     * <h2>加密 - 模式 ECB</h2>
     * @param text 需要加密的文本内容
     * @param key 加密的密钥 key
     * */
    public static String encrypt(String text, String key){
        if (isEmpty(text) || isEmpty(key)) {
            return null;
        }

        try {
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance(AES_ECB);

            SecretKeySpec secretKeySpec = getSecretKeySpec(key);

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            // 加密字节数组
            byte[] encryptedBytes = cipher.doFinal(getBytes(text));

            // 将密文转换为 Base64 编码字符串
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static byte[] decrypt(byte[] textBytes, String key){
        try {
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance(AES_ECB);
            SecretKeySpec secretKeySpec = getSecretKeySpec(key);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            // 解密字节数组
            byte[] decryptedBytes = cipher.doFinal(textBytes);
            return decryptedBytes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <h2>加密 - 自定义加密模式</h2>
     * @param text 需要加密的文本内容
     * @param key 加密的密钥 key
     * @param iv 初始化向量
     * @param mode 加密模式
     * */
    public static String encrypt(String text, String key, String iv, String mode){
        if (isEmpty(text) || isEmpty(key) || isEmpty(iv)) {
            return null;
        }

        try {
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance(mode);

            SecretKeySpec secretKeySpec = getSecretKeySpec(key);

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(getBytes(iv)));

            // 加密字节数组
            byte[] encryptedBytes = cipher.doFinal(getBytes(text));

            // 将密文转换为 Base64 编码字符串
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static String decrypt(byte[] textBytes, String key, String iv, String mode){


        try {
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance(mode);

            SecretKeySpec secretKeySpec = getSecretKeySpec(key);

            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(getBytes(iv)));

            // 解密字节数组
            byte[] decryptedBytes = cipher.doFinal(textBytes);

            // 将明文转换为字符串
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    static void decryptData(String in,String out) throws IOException {
        byte[] text = Files.readAllBytes(Paths.get(in));
        String key  = ""; // 填入自己的16字节的密钥
        byte[] strOut = decrypt(text, key);
        byte[] strOutCopy = new byte[strOut.length - 5];
        for(int i = 0 ;i < strOutCopy.length;i++){
            strOutCopy[i]  = strOut[i+4];
        }
        Files.write(Paths.get(out),strOutCopy);
    }



    public static void main(String[] args) throws IOException {
        


    }
}

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!以下是一个示例的完整代码,用于在Android中使用Java实现AES加密和解密: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class AESUtil { private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String CHARSET = "UTF-8"; private static byte[] encrypt(byte[] key, byte[] initVector, byte[] value) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(value); } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] decrypt(byte[] key, byte[] initVector, byte[] encrypted) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(encrypted); } catch (Exception e) { e.printStackTrace(); } return null; } public static String encrypt(String key, String initVector, String value) { try { byte[] encrypted = encrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), value.getBytes(CHARSET)); return Base64.encodeToString(encrypted, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(String key, String initVector, String encrypted) { try { byte[] decoded = Base64.decode(encrypted, Base64.DEFAULT); byte[] decrypted = decrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), decoded); return new String(decrypted, CHARSET); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 使用示例: ```java String key = "0123456789abcdef"; // 16字节的密钥 String initVector = "ABCDEF0123456789"; // 16字节的初始向量 String originalText = "Hello, AES!"; String encryptedText = AESUtil.encrypt(key, initVector, originalText); String decryptedText = AESUtil.decrypt(key, initVector, encryptedText); System.out.println("Original Text: " + originalText); System.out.println("Encrypted Text: " + encryptedText); System.out.println("Decrypted Text: " + decryptedText); ``` 请注意,这只是一个简单的示例代码,并不涵盖所有的错误处理和最佳实践。在实际使用中,请根据需要进行适当的异常处理和安全性考虑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值