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;
              }
          }


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


          網站導航:
           
          主站蜘蛛池模板: 遵义市| 南通市| 同德县| 拉孜县| 汪清县| 闻喜县| 延庆县| 新平| 和顺县| 景泰县| 察隅县| 郓城县| 涟水县| 申扎县| 西平县| 黔南| 蒙山县| 黄骅市| 汝阳县| 申扎县| 鄂尔多斯市| 博客| 溧水县| 宜川县| 特克斯县| 邳州市| 上思县| 当雄县| 华蓥市| 东莞市| 秦安县| 蓝田县| 广西| 日喀则市| 凤翔县| 简阳市| 清丰县| 阿拉善左旗| 鹤山市| 绥宁县| 宝应县|