AES加密--JAVA实现

  1. AES
    AES是常用的对称加密技术,比DES有更高的安全性。

在写CP-ABE系统的时间使用AES加密密文文件,ABE加密了一个Element(JPBC库),属于常见的加密体制。

下面代码的AES,一个是以文件流的形式加密文件,一个是直接加密字符串

代码部分

public class Aes {
       private static final String ALGORITHM = "AES";
        private static final int KEY_SIZE = 128;
        private static final int CACHE_SIZE = 1024;
        
        public static void encryptFile(Element m,String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath); 
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            destFile.createNewFile();
            InputStream in = new FileInputStream(sourceFile);
            OutputStream out = new FileOutputStream(destFile);
           // Key k = toKey(Base64.decode(key));
            //byte[] raw = k.getEncoded(); 
            
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(m.toBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            //byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key1);// 初始化
            //byte[] result = cipher.doFinal(byteContent);

            //SecretKeySpec secretKeySpec = new SecretKeySpec(key,"AES"); 
            //Cipher cipher = Cipher.getInstance("AES"); 
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            CipherInputStream cin = new CipherInputStream(in, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = cin.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                //System.out.println("加密成功");
                out.flush();
            }
            out.close();
            cin.close();
            in.close();
        }
    }
    
    /**
     * <p>
     * 解密
     * </p>
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */

    /**
     * <p>
     * 文件解密
     * </p>
     * 
     * @param key
     * @param sourceFilePath
     * @param destFilePath
     * @throws Exception
     */
    public static void decryptFile(Element m, String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath); 
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            destFile.createNewFile();
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(destFile);
            //Key k = toKey(Base64.decode(key));
           // byte[] raw = k.getEncoded(); 
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(m.toBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key1);// 初始化
            //byte[] result = cipher.doFinal(content);
            
            //SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES"); 
            //Cipher cipher = Cipher.getInstance("AES"); 
            //cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            CipherOutputStream cout = new CipherOutputStream(out, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                cout.write(cache, 0, nRead);
                cout.flush();
            }
            cout.close();
            out.close();
            in.close();
        }
    }
    public static byte[] encrypt(String content, Element m) {
        try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(m.toBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                byte[] byteContent = content.getBytes();
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return result; // 加密
        } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
        } catch (NoSuchPaddingException e) {
                e.printStackTrace();
        } catch (InvalidKeyException e) {
                e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
        } catch (BadPaddingException e) {
                e.printStackTrace();
        }
        return null;
}
public static byte[] decrypt(byte[] content, Element m) {
        try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(m.toBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(content);
                return result; // 加密
        } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
        } catch (NoSuchPaddingException e) {
                e.printStackTrace();
        } catch (InvalidKeyException e) {
                e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
        } catch (BadPaddingException e) {
                e.printStackTrace();
        }
        return null;
}

public static byte[] parseHexStr2Byte(String hexStr) {  
    if (hexStr.length() < 1)  
            return null;  
    byte[] result = new byte[hexStr.length()/2];  
    for (int i = 0;i< hexStr.length()/2; i++) {  
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
            result[i] = (byte) (high * 16 + low);  
    }  
    return result;  
}
public static String parseByte2HexStr(byte buf[]) {  
    StringBuffer sb = new StringBuffer();  
    for (int i = 0; i < buf.length; i++) {  
            String hex = Integer.toHexString(buf[i] & 0xFF);  
            if (hex.length() == 1) {  
                    hex = '0' + hex;  
            }  
            sb.append(hex.toUpperCase());  
    }  
    return sb.toString();  
} 
public static void writeTxt(String inputfile,String str) {
    try {
        FileWriter writ = new FileWriter(inputfile);
        //writ.write("");//清空原文件内容
        writ.write(str);
        writ.flush();
        writ.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    
      public static void main(String[] rags) { 
          float time1,time2;
          String content = "test2222"; 
          String password = "12345678"; 
          String inputfile = "D:/DO/向琴毕业设计.txt"; 
          String outputfile = "D:/DO/向琴毕业设计密文.txt"; 
          String ouput1file = "D:/DO/向琴毕业设计明文1.txt";
      Cpabe cpabe = new Cpabe(Util.curveParams); 
      Element m = cpabe.pp.p.getGT().newRandomElement(); // 加密 
      System.out.println("加密前:" +content);
//      try { 
//    encryptFile(m, inputfile, outputfile); 
//    decryptFile(m,outputfile, ouput1file); 
//    } 
//      catch (Exception e) 
//      { // TODO Auto-generated catchblock 
//          e.printStackTrace(); 
//      } 
      Date d1 = new Date();
      byte[] encryptResult = encrypt(content, m); 
      Date d2 = new Date();
    //  String k = parseByte2HexStr(encryptResult); 
      // System.out.println("加密后:"+k);
       //解密 //
       byte[] decryptResult = decrypt(encryptResult, m);
       Date d3 = new Date();
      //System.out.println("解密后:" + new String(decryptResult));
       System.out.println("加密时间:"+(d2.getTime()-d1.getTime()));
       System.out.println("加密时间:"+(d3.getTime()-d3.getTime()));
//      }
      }
     
}

代码如上,看到一些博客说AES加密时间和解密时间相比应该是差不多的,但是博主测试AES加密时间为300ms作用,解密时间却只有20ms,感觉可能是jar包的问题。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用javax.crypto包来实现AES-128加密算法。下面是一个简单的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static String encrypt(String plaintext, 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(plaintext.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String ciphertext, 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(ciphertext)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { try { String plaintext = "Hello, World!"; String key = "0123456789abcdef"; // 16字节的密钥 String ciphertext = AESUtil.encrypt(plaintext, key); System.out.println("加密后的密文:" + ciphertext); String decryptedText = AESUtil.decrypt(ciphertext, key); System.out.println("解密后的明文:" + decryptedText); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意:在实际使用中,应该使用更安全的方式来存储密钥,例如使用密钥管理系统(Key Management System)来保护密钥的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值