欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AES加密--JAVA实现

程序员文章站 2024-01-16 20:36:34
...
  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包的问题。

相关标签: AES 加密