public static void crypt(String inFilename, String outFilename, int mode) { InputStream in = null; OutputStream out = null; ObjectInputStream keyin = null; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); keyin = new ObjectInputStream(new FileInputStream(keyFilename)); // 获取到密钥 Key key = (Key) keyin.readObject(); // 使用AES算法获取密码对象 Cipher cipher = Cipher.getInstance("AES"); // 通过设置模式和密钥来初始化 cipher.init(mode, key); // 获取密码块大小,16 int blockSize = cipher.getBlockSize(); // 该密码块对应的输出缓存区大小,用于存放密码对象输出的数据块 int outputSize = cipher.getOutputSize(blockSize); byte[] inBytes = new byte[blockSize]; byte[] outBytes = new byte[outputSize]; int length = 0; boolean more = true; while (more) { length = in.read(inBytes); // 如果能读到blockSize大小的块 if (length == blockSize) { // 数据块存入outBytes int outLength = cipher.update(inBytes, 0, blockSize, outBytes); out.write(outBytes, 0, outLength); } else { more = false; } } // 如果最后一个输入数据块的字节数小于blockSize,剩下的字节将会自动填充 if (length > 0) { outBytes = cipher.doFinal(inBytes, 0, length); } else { outBytes = cipher.doFinal(); } out.write(outBytes); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } finally { Closer.close(in); Closer.close(out); Closer.close(keyin); } }
public static void generateKey(String filename) { ObjectOutputStream out = null; try { // 使用AES算法获取密钥的 KeyGenerator对象 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); // 用随机源初始化密钥发生器 SecureRandom random = new SecureRandom(); keyGenerator.init(random); // 生成一个密钥 SecretKey key = keyGenerator.generateKey(); // 把密钥输出到文件 out = new ObjectOutputStream(new FileOutputStream(filename)); out.writeObject(key); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { Closer.close(out); } }