读书人

java兑现DES加密算法

发布时间: 2012-10-25 10:58:58 作者: rapoo

java实现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;
? ? }


文件采用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();
? ? ? ? is.close();
? ? }

1 楼 fjlyxx 2008-12-13 你测试下在WEBSPEHE上加密,在TOMCAT上解密 看看能不能解开/

读书人网 >软件架构设计

热点推荐