JAVA实现DES加密算法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
数据结构算法:java 实现 DES 加密算法 java 实现 DES 加密算法 为了实现一对密钥对整个项目所有加密解密文件都适用的方法,考试,大提示采用先
生成一对密钥.保存到 xml 文件中,以后获得私匙和公钥只需要从 xml 文件中取得就可以了. /** * 把成生的一对密钥保存到 DesKey.xml 文件中 */ public static void saveDesKey(){ try { SecureRandom sr = new SecureRandom(); //为我们选择的 DES 算法生成一个 KeyGenerator 对象 KeyGenerator kg = KeyGenerator.getInstance (\"DES\" ); kg.init (sr); FileOutputStream fos = new FileOutputStream(\"C:/DesKey.xml\"); ObjectOutputStream oos = new ObjectOutputStream(fos); //生成密钥 Key key = kg.generateKey(); oos.writeObject(key); oos.close(); } catch (Exception e) { e.printStackTrace(); } } 获取密钥方法如下: /** * 获得 DES 加密的密钥。在交易处理的过程中应该定时更 * 换密钥。需要 JCE 的支持,如果 jdk 版本低于 1.4,则需要 * 安装 jce-1_2_2 才能正常使用。 * @return Key 返回对称密钥 */ public static Key getKey() { Key kp = null; try { String fileName = \"conf/DesKey.xml\"; InputStream is = DesUtil.class.getClassLoader() .getResourceAsStream(fileName); ObjectInputStream oos = new ObjectInputStream(is); kp = (Key) oos.readObject(); oos.close(); } catch (Exception e) { e.printStackTrace(); } return kp; }
is.close(); }
Biblioteka Baidu
文件采用 DES 算法加密文件 /** * 文件 file 进行加密并保存目标文件 destFile 中 * @param file * 要加密的文件 如 c:/test/srcFile.txt * @param destFile * 加密后存放的文件名 如 c:/加密后文件.txt */ public static void encrypt(String file, String destFile) throws Exception { Cipher cipher = Cipher.getInstance(\"DES\"); cipher.init(Cipher.ENCRYPT_MODE, getKey()); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherInputStream cis = new CipherInputStream(is, cipher); byte[] buffer = new byte[1024]; int r; while ((r = cis.read(buffer)) > 0) { out.write(buffer, 0, r); } cis.close(); is.close(); out.close(); } 文件采用 DES 算法解密文件 /** * 文件 file 进行加密并保存目标文件 destFile 中 * @param file * 已加密的文件 如 c:/加密后文件.txt * @param destFile * 解密后存放的文件名 如 c:/ test/解密后文件.txt */ public static void decrypt(String file, String dest) throws Exception { Cipher cipher = Cipher.getInstance(\"DES\"); cipher.init(Cipher.DECRYPT_MODE, getKey()); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024]; int r; while ((r = is.read(buffer)) >= 0) { cos.write(buffer, 0, r); } cos.close(); out.close();
相关文档
最新文档