posts - 66,comments - 41,trackbacks - 0
                  最近HR要求把公司的HRMS一些關鍵數據加密,加密的數據應該包括兩方面,一個是當然Spring讀取的屬性文件(e.g :System.properties),還有一個是數據庫的關鍵字段(不知道當初設計時為什么沒有實現加密,我真是搞不懂,現在扔給我,惡改ing)。
                 關于加密properties文件,原理就是寫一個新的類如EncryptPropertyPlaceholderConfigurer繼承PropertyPlaceholderConfigurer類,然后在applicationContext-resources.xml的“propertyConfig”中的class改成你新寫的這個類,如下所示:

           

           <bean id="propertyConfig"
                    class
          ="org.kylixlu.framework.spring.bean.ReadEncryptedPropertyPlaceholderConfigurer">
                  
          <property name="locations">
                      
          <list>
                          
          <value>classpath:system.properties</value>
                      
          </list>
                  
          </property>
                  
          <property name="keyLocation" value="classpath:key.dat"/>
                  
          <property name="fileEncoding" value="utf-8"/>

              
          </bean>

               這個EncryptPropertyPlaceholderConfigurer的代碼如下:
           1package org.kylixlu.framework.spring.bean;
           2
           3import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
           4import org.springframework.core.io.Resource;
           5import org.springframework.util.PropertiesPersister;
           6import org.springframework.util.DefaultPropertiesPersister;
           7
           8import java.util.Properties;
           9import java.io.IOException;
          10import java.io.InputStream;
          11import java.io.InputStreamReader;
          12import java.security.Key;
          13
          14import org.kylixlu.component.crypto.DESEncryptUtil;
          15
          16//import org.kylixlu.component.crypto.DESEncryptUtil;
          17
          18/**
          19 * Created by IntelliJ IDEA.
          20 * User: Lu Yuxiang
          21 * Date: 2008-1-2
          22 * Time: 17:53:25
          23 * To change this template use File | Settings | File Templates.
          24 */

          25
          26public class ReadEncryptedPropertyPlaceholderConfigurer
          27        extends
          28        PropertyPlaceholderConfigurer {
          29    private Resource[] locations;
          30    private Resource keyLocation;
          31    private String fileEncoding;
          32
          33    public void setFileEncoding(String fileEncoding) {
          34        this.fileEncoding = fileEncoding;
          35    }

          36
          37    public void setKeyLocation(Resource keyLocation) {
          38        this.keyLocation = keyLocation;
          39    }

          40
          41    public void setLocations(Resource[] locations) {
          42        this.locations = locations;
          43    }

          44
          45    public void loadProperties(Properties props) throws IOException {
          46        if (this.locations != null{
          47            PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
          48            for (int i = 0; i < this.locations.length; i++{
          49                Resource location = this.locations[i];
          50                InputStream is = null;
          51
          52                try {
          53                    is = location.getInputStream();
          54                    Key key = DESEncryptUtil.getKey(keyLocation
          55                            .getInputStream());
          56                    is = DESEncryptUtil.doDecrypt(key, is);
          57                    if (fileEncoding != null{
          58                        propertiesPersister.load(props, new InputStreamReader(is,
          59                                fileEncoding));
          60                    }
           else {
          61                        propertiesPersister.load(props, is);
          62                    }

          63                }
           finally {
          64                    if (is != null)
          65                        is.close();
          66                }

          67            }

          68        }

          69    }

          70}

          71
          下面再給出加密類的代碼(這個加密類網上很多,直接down了一個,DES算法的)
          package org.kylixlu.component.crypto;

          ///**
          // * Created by IntelliJ IDEA.
          // * User: Lu Yuxiang
          // * Date: 2008-1-2
          // * Time: 18:36:23
          // * To change this template use File | Settings | File Templates.
          // */
          import java.io.ByteArrayInputStream;
          import java.io.ByteArrayOutputStream;
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.InputStream;
          import java.io.ObjectInputStream;
          import java.io.ObjectOutputStream;
          import java.security.Key;
          import java.security.NoSuchAlgorithmException;
          import java.security.SecureRandom;
          import java.security.Security;

          import javax.crypto.Cipher;
          import javax.crypto.KeyGenerator;

          public class DESEncryptUtil {
              public static Key createKey() throws NoSuchAlgorithmException {
                  Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);
                  KeyGenerator generator = KeyGenerator.getInstance("DES");
                  generator.init(new SecureRandom());
                  Key key = generator.generateKey();
                  return key;
              }

              public static Key getKey(InputStream is) {
                  try {
                      ObjectInputStream ois = new ObjectInputStream(is);
                      return (Key) ois.readObject();
                  } catch (Exception e) {
                      e.printStackTrace();
                      throw new RuntimeException(e);
                  }
              }


              private static byte[] doEncrypt(Key key, byte[] data) {
                  try {
                      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                      cipher.init(Cipher.ENCRYPT_MODE, key);
                      byte[] raw = cipher.doFinal(data);
                      return raw;
                  } catch (Exception e) {
                      e.printStackTrace();
                      throw new RuntimeException(e);
                  }
              }

              public static InputStream doDecrypt(Key key, InputStream in) {
                  try {
                      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                      cipher.init(Cipher.DECRYPT_MODE, key);

                      ByteArrayOutputStream bout = new ByteArrayOutputStream();
                      byte[] tmpbuf = new byte[1024];
                      int count = 0;
                      while ((count = in.read(tmpbuf)) != -1) {
                          bout.write(tmpbuf, 0, count);
                          tmpbuf = new byte[1024];
                      }
                      in.close();

                      byte[] orgData = bout.toByteArray();
                      byte[] raw = cipher.doFinal(orgData);

                      ByteArrayInputStream bin = new ByteArrayInputStream(raw);
                      return bin;
                  } catch (Exception e) {
                      e.printStackTrace();
                      throw new RuntimeException(e);
                  }
              }

              public static void main(String[] args) throws Exception {
          //        args = new String[]{
          //                "decrypt",
          //                "f:\\en_system.properties",
          //                "f:\\key.dat"};
                  args = new String[]{
                          "encrypt",
                          "f:\\system.properties",
                          "f:\\key.dat"};
          //        args = new String[]{
          //                "key",
          //                "f:\\key.dat"};
                  if (args.length == 2 && args[0].equals("key")) {// 生成密鑰文件
                      Key key = DESEncryptUtil.createKey();
                      ObjectOutputStream oos = new ObjectOutputStream(
                              new FileOutputStream(args[1]));
                      oos.writeObject(key);
                      oos.close();
                      System.out.println("成功生成密鑰文件。");
                  } else if (args.length == 3 && args[0].equals("encrypt")) {//對文件進行加密
                      File file = new File(args[1]);
                      FileInputStream in = new FileInputStream(file);
                      ByteArrayOutputStream bout = new ByteArrayOutputStream();
                      byte[] tmpbuf = new byte[1024];
                      int count = 0;
                      while ((count = in.read(tmpbuf)) != -1) {
                          bout.write(tmpbuf, 0, count);
                          tmpbuf = new byte[1024];
                      }
                      in.close();
                      byte[] orgData = bout.toByteArray();
                      Key key = getKey(new FileInputStream(args[2]));
                      byte[] raw = DESEncryptUtil.doEncrypt(key, orgData);
                      file = new File("\\en_" + file.getName());

                      FileOutputStream out = new FileOutputStream(file);
                      out.write(raw);
                      out.close();
                      System.out.println("成功加密,加密文件位于:"+file.getAbsolutePath());
                  }
            else if (args.length == 3 && args[0].equals("decrypt")) {

                      File file = new File(args[1]);
                      FileInputStream fis = new FileInputStream(file);
                      Key key = getKey(new FileInputStream(args[2]));
                      InputStream raw = DESEncryptUtil.doDecrypt(key, fis);

                      ByteArrayOutputStream bout = new ByteArrayOutputStream();
                      byte[] tmpbuf = new byte[1024];
                      int count = 0;
                      while ((count = raw.read(tmpbuf)) != -1) {
                          bout.write(tmpbuf, 0, count);
                          tmpbuf = new byte[1024];
                      }
                      raw.close();
                      byte[] orgData = bout.toByteArray();
                      file = new File(file.getParent() + "\\rs_" + file.getName());
                      FileOutputStream fos = new FileOutputStream(file);
                      fos.write(orgData);
                      System.out.println("成功解密,解密文件位于:"+file.getAbsolutePath());
                  }
              }
          }




          MSN:
          posted on 2008-01-13 13:18 kylixlu 閱讀(2295) 評論(2)  編輯  收藏 所屬分類: Spring

          FeedBack:
          # re: 給Spring的.properties文件加密
          2008-01-14 10:13 | honeyjava
          有這樣開源工具  回復  更多評論
            
          # re: 給Spring的.properties文件加密[未登錄]
          2008-01-14 14:37 | 陸昱相
          樓上應該說的是jasypt吧,HOHO,不會用啊  回復  更多評論
            

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


          網站導航:
           
          主站蜘蛛池模板: 嘉善县| 全椒县| 胶州市| 中西区| 工布江达县| 姜堰市| 扎兰屯市| 普兰县| 梁河县| 霍城县| 龙泉市| 安宁市| 忻城县| 洛川县| 景泰县| 苏尼特左旗| 昌图县| 股票| 大化| 陆良县| 永川市| 汪清县| 晋城| 孟连| 双流县| 柏乡县| 剑川县| 文水县| 昔阳县| 新野县| 湟中县| 洛阳市| 肃北| 海安县| 明溪县| 腾冲县| 基隆市| 饶阳县| 宝坻区| 林西县| 洞头县|