【转】Java Cipher类 DES算法(加密与解密)
2015-12-02 10:37
555 查看
Java Cipher类 DES算法(加密与解密)
1.加密解密类
2.测试
1.加密解密类
import java.security.*; import javax.crypto.*; import java.io.*; //对称加密器 public class CipherMessage { private String algorithm; // 算法,如DES private Key key; // 根据算法对应的密钥 private String plainText; // 明文 KeyGenerator keyGenerator; Cipher cipher; // 函数进行初始化 CipherMessage(String alg, String msg) { algorithm = alg; plainText = msg; } // 加密函数,将原文加密成密文 public byte[] CipherMsg() { byte[] cipherText = null; try { // 生成Cipher对象 cipher = Cipher.getInstance(algorithm); // 用密钥加密明文(plainText),生成密文(cipherText) cipher.init(Cipher.ENCRYPT_MODE, key); // 操作模式为加密(Cipher.ENCRYPT_MODE),key为密钥 cipherText = cipher.doFinal(plainText.getBytes()); // 得到加密后的字节数组 // String str = new String(cipherText); } catch (Exception e) { e.printStackTrace(); } return cipherText; } // 解密函数,将密文解密回原文 public String EncipherMsg(byte[] cipherText, Key k) { byte[] sourceText = null; try { cipher.init(Cipher.DECRYPT_MODE, k); // 操作模式为解密,key为密钥 sourceText = cipher.doFinal(cipherText); } catch (Exception e) { e.printStackTrace(); } return new String(sourceText); } // 生成密钥 public Key initKey() { try { // 初始化密钥key keyGenerator = KeyGenerator.getInstance(algorithm); keyGenerator.init(56); // 选择DES算法,密钥长度必须为56位 key = keyGenerator.generateKey(); // 生成密钥 } catch (Exception ex) { ex.printStackTrace(); } return key; } // 获取Key类型的密钥 public Key getKey() { return key; } // 获取Key类型的密钥 public Key getKey(byte[] k) { try { key = cipher.unwrap(k, algorithm, Cipher.DECRYPT_MODE); } catch (Exception ex) { ex.printStackTrace(); } return key; } // 获取密钥包装成byte[]类型的 public byte[] getBinaryKey(Key k) { byte[] bk = null; try { bk = cipher.wrap(k); } catch (Exception ex) { ex.printStackTrace(); } return bk; } }
2.测试
import java.security.*; import javax.crypto.*; import java.io.*; public class TestMain { public static void main(String[] args) { String algorithm = "DES"; // 定义加密算法,可用 DES,DESede,Blowfish String message = "Hello World. 这是待加密的信息"; // 生成个DES密钥 Key key; CipherMessage cm = new CipherMessage(algorithm, message); key = cm.initKey(); byte[] msg = cm.CipherMsg(); System.out.println("加密后的密文为:" + new String(msg)); // System.out.println("密钥为:"+new String(cm.getBinaryKey(key))); System.out.println(cm.getBinaryKey(key)); System.out.println("解密密文为:" + cm.EncipherMsg(msg, key)); } }
相关文章推荐
- Spring事务配置的五种方式和spring里面事务的传播属性和事务隔离级别
- Java:单例模式的七种写法
- spring factory-method
- java synchronized详解
- 【Information:java: javacTask: 源发行版 1.7 需要目标发行版 1.7】
- autoload-cache-2.4 发布
- JAVA AQS源码分析
- SpringMVC整合Tiles框架
- Java String操作 trim()
- Java 接口和抽象类区别
- java设计模式----享元模式
- Java中finalize()用法
- Java内联函数
- 【Java EE (Struts2 + Spring + Hibernate)开发】:Web 之 【JSP基础知识】
- Spring MVC集成Tiles使用方法
- Java - 关键字 final 的用法总结
- eclipse android SDK离线
- 从头认识java-11.4 正则表达式(1)-感性认知
- Spring注解@Component、@Repository、@Service、@Controller区别
- java Io流文件夹的拷贝