2016-10-13 00:16:48 点击量:92 标签: 收藏本文
java代码
- import java.io.IOException;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESKeySpec;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- public class DES {
- private byte[] desKey;
- public DES(String desKey) {
- this.desKey = desKey.getBytes();
- }
- public byte[] desEncrypt(byte[] plainText) throws Exception {
- SecureRandom sr = new SecureRandom();
- byte rawKeyData[] = desKey;
- DESKeySpec dks = new DESKeySpec(rawKeyData);
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.ENCRYPT_MODE, key, sr);
- byte data[] = plainText;
- byte encryptedData[] = cipher.doFinal(data);
- return encryptedData;
- }
- public byte[] desDecrypt(byte[] encryptText) throws Exception {
- SecureRandom sr = new SecureRandom();
- byte rawKeyData[] = desKey;
- DESKeySpec dks = new DESKeySpec(rawKeyData);
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.DECRYPT_MODE, key, sr);
- byte encryptedData[] = encryptText;
- byte decryptedData[] = cipher.doFinal(encryptedData);
- return decryptedData;
- }
- public String encrypt(String input) throws Exception {
- return base64Encode(desEncrypt(input.getBytes()));
- }
- public String decrypt(String input) throws Exception {
- byte[] result = base64Decode(input);
- return new String(desDecrypt(result));
- }
- public static String base64Encode(byte[] s) {
- if (s == null)
- return null;
- BASE64Encoder b = new sun.misc.BASE64Encoder();
- return b.encode(s);
- }
- public static byte[] base64Decode(String s) throws IOException {
- if (s == null)
- return null;
- BASE64Decoder decoder = new BASE64Decoder();
- byte[] b = decoder.decodeBuffer(s);
- return b;
- }
- public static void main(String[] args) throws Exception {
- String key = "abcdefgh";
- String input = "a";
- DES crypt = new DES(key);
- System.out.println("Encode:" + crypt.encrypt(input));
- System.out.println("Decode:" + crypt.decrypt(crypt.encrypt(input)));
- }
- }
我们是一家提供综合软件外包与弱电工程服务的技术公司。
业务涵盖定制软件、管理系统、网站、小程序、APP、系统集成、网络布线、监控安防、门禁、机房建设及长期技术维护。
公司地址:湖北省宜昌市伍家岗区东站二路6号三峡(宜昌)大数据产业园海洋馆二楼A203室