I'll be back!

            Focus on BPM, celebrate PegaRULES Process Commander (PRPC)
          posts - 76, comments - 161, trackbacks - 0, articles - 2
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理
          DESede又稱Triple-DES即三重DES加密算法,加強了DES的安全性,但速度稍慢,它是一種對稱加密算法,加密解密都是用同一個密鑰。本文介紹使用Java自帶的API實現DEDede加密解密。

          Bouncy Castle也支持DES算法,具體沒有深入研究,有興趣的可以下載相應的API進行測試。
          http://www.bouncycastle.org/

          以下代碼基本上覆蓋了生成密鑰以及加密解密的全過程,拷貝代碼可以直接運行。(代碼摘自網絡)
          每次生成密鑰都會不一樣,一般來說密鑰需要生成文件并妥善保存。
          DESedeCoder.java
          package com.zolly.bouncycastle;

          import java.io.BufferedOutputStream;
          import java.io.FileOutputStream;
          import java.security.Key;
          import javax.crypto.Cipher;
          import javax.crypto.KeyGenerator;
          import javax.crypto.SecretKey;
          import javax.crypto.SecretKeyFactory;
          import javax.crypto.spec.DESedeKeySpec;

          import com.sun.org.apache.xml.internal.security.utils.Base64;

          /**
           * DESede對稱加密算法演示
           * 
           * 
          @author zolly
           * 
          */
          public class DESedeCoder {
              /**
               * 密鑰算法
               * 
          */
              public static final String KEY_ALGORITHM = "DESede";

              /**
               * 加密/解密算法/工作模式/填充方式
               * 
          */
              public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";

              /**
               * 
               * 生成密鑰
               * 
               * 
          @return byte[] 二進制密鑰
               * 
          */
              public static byte[] initkey() throws Exception {

                  // 實例化密鑰生成器
                  KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
                  // 初始化密鑰生成器
                  kg.init(168);
                  // 生成密鑰
                  SecretKey secretKey = kg.generateKey();
                  // 獲取二進制密鑰編碼形式
                  
                  byte[] key = secretKey.getEncoded();
                  BufferedOutputStream keystream = 
                          new BufferedOutputStream(new FileOutputStream("DESedeKey.dat"));
                  keystream.write(key, 0, key.length);
                  keystream.flush();
                  keystream.close();
                  
                  return key;
              }

              /**
               * 轉換密鑰
               * 
               * 
          @param key
               *            二進制密鑰
               * 
          @return Key 密鑰
               * 
          */
              public static Key toKey(byte[] key) throws Exception {
                  // 實例化Des密鑰
                  DESedeKeySpec dks = new DESedeKeySpec(key);
                  // 實例化密鑰工廠
                  SecretKeyFactory keyFactory = SecretKeyFactory
                          .getInstance(KEY_ALGORITHM);
                  // 生成密鑰
                  SecretKey secretKey = keyFactory.generateSecret(dks);
                  return secretKey;
              }

              /**
               * 加密數據
               * 
               * 
          @param data
               *            待加密數據
               * 
          @param key
               *            密鑰
               * 
          @return byte[] 加密后的數據
               * 
          */
              public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
                  // 還原密鑰
                  Key k = toKey(key);
                  // 實例化
                  Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                  // 初始化,設置為加密模式
                  cipher.init(Cipher.ENCRYPT_MODE, k);
                  // 執行操作
                  return cipher.doFinal(data);
              }

              /**
               * 解密數據
               * 
               * 
          @param data
               *            待解密數據
               * 
          @param key
               *            密鑰
               * 
          @return byte[] 解密后的數據
               * 
          */
              public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
                  // 歡迎密鑰
                  Key k = toKey(key);
                  // 實例化
                  Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                  // 初始化,設置為解密模式
                  cipher.init(Cipher.DECRYPT_MODE, k);
                  // 執行操作
                  return cipher.doFinal(data);
              }

              /**
               * 進行加解密的測試
               * 
               * 
          @throws Exception
               
          */
              public static void main(String[] args) throws Exception {
                  String str = "DESede";
                  System.out.println("原文:" + str);
                  // 初始化密鑰
                  byte[] key = DESedeCoder.initkey();
                  System.out.println("密鑰:" + Base64.encode(key));
                  // 加密數據
                  byte[] data = DESedeCoder.encrypt(str.getBytes(), key);
                  System.out.println("加密后:" + Base64.encode(data));
                  // 解密數據
                  data = DESedeCoder.decrypt(data, key);
                  System.out.println("解密后:" + new String(data));
              }
          }


          正對以上代碼,我進行了適當修改,使其變得更加實用。我的主要應用是把客戶的數據加密保存到數據庫,取出來的時候再解密,保證數據庫數據的安全。注意我固定了密鑰,以防密鑰一旦丟失,所有數據都變成亂碼了,固定密鑰安全性有所降低,但是對數據庫字段加密安全性已經足夠了。
          DESedeTest.java
          package com.zolly.bouncycastle;

          import java.security.InvalidKeyException;
          import java.security.NoSuchAlgorithmException;
          import java.security.spec.InvalidKeySpecException;

          import javax.crypto.BadPaddingException;
          import javax.crypto.Cipher;
          import javax.crypto.IllegalBlockSizeException;
          import javax.crypto.NoSuchPaddingException;
          import javax.crypto.SecretKey;
          import javax.crypto.SecretKeyFactory;
          import javax.crypto.spec.DESedeKeySpec;

          import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
          import com.sun.org.apache.xml.internal.security.utils.Base64;

          public class DESedeTest {

              /**
               * 
          @param args
               
          */
              public static void main(String[] args) {

                  String strText = "This is a testing";

                  String text1 = DESedeTest.encryptProperty(strText);

                  String text2 = DESedeTest.decryptProperty(text1);

                  System.out.println(text1);

                  System.out.println(text2);
              }

              public static String encryptProperty(String clearText) {

                  String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";

                  byte[] key = null;

                  try {
                      key = Base64.decode(KEY_STRING);
                  } catch (Base64DecodingException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }

                  return DESedeTest.performDESedeCoder(clearText, key, true);
              }

              public static String decryptProperty(String cipherText) {

                  String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";

                  byte[] key = null;

                  try {
                      key = Base64.decode(KEY_STRING);
                  } catch (Base64DecodingException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }

                  return DESedeTest.performDESedeCoder(cipherText, key, false);
              }

              public static String performDESedeCoder(String inputValue, byte[] key,
                      boolean encrypt) {
                  String rtnValue = "";

                  String KEY_ALGORITHM = "DESede";
                  String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";

                  byte[] data = null;
                  try {
                      DESedeKeySpec dks = new DESedeKeySpec(key);

                      SecretKeyFactory keyFactory = SecretKeyFactory
                              .getInstance(KEY_ALGORITHM);

                      SecretKey secretKey = keyFactory.generateSecret(dks);

                      Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

                      byte[] input = null;
                      if (encrypt) {
                          cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                          input = inputValue.getBytes();
                      } else {
                          cipher.init(Cipher.DECRYPT_MODE, secretKey);
                          input = Base64.decode(inputValue);
                      }

                      data = cipher.doFinal(input);
                  } catch (InvalidKeyException e) {
                      System.out.println(e.getMessage());
                  } catch (NoSuchAlgorithmException e) {
                      System.out.println(e.getMessage());
                  } catch (InvalidKeySpecException e) {
                      System.out.println(e.getMessage());
                  } catch (NoSuchPaddingException e) {
                      System.out.println(e.getMessage());
                  } catch (IllegalBlockSizeException e) {
                      System.out.println(e.getMessage());
                  } catch (BadPaddingException e) {
                      System.out.println(e.getMessage());
                  } catch (Base64DecodingException e) {
                      System.out.println(e.getMessage());
                  }

                  if (data == null) {
                      rtnValue = inputValue;
                  } else {
                      if (encrypt) {
                          rtnValue = com.sun.org.apache.xml.internal.security.utils.Base64
                                  .encode(data);
                      } else {
                          rtnValue = new String(data);
                      }
                  }

                  return rtnValue;
              }
          }


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 东乌| 阿巴嘎旗| 蕉岭县| 陵水| 隆德县| 米泉市| 海阳市| 昌黎县| 财经| 绩溪县| 武清区| 石家庄市| 禹州市| 岗巴县| 荣成市| 朔州市| 栾城县| 龙岩市| 霍山县| 克山县| 崇文区| 报价| 海丰县| 宁城县| 富平县| 上犹县| 宣武区| 新田县| 灌云县| 民乐县| 启东市| 墨玉县| 菏泽市| 交城县| 仙桃市| 剑川县| 赤峰市| 金湖县| 平阴县| 绿春县| 惠水县|