`
wlhok
  • 浏览: 56211 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

DES加密/解密操作

    博客分类:
  • Java
阅读更多

生成DES密钥、保存密钥到文件、从文件读取密钥、加密、解密等操作。

java 代码
  1. import java.io.ByteArrayOutputStream;   
  2. import java.io.File;   
  3. import java.io.FileInputStream;   
  4. import java.io.FileNotFoundException;   
  5. import java.io.FileOutputStream;   
  6. import java.io.IOException;   
  7. import java.io.OutputStream;   
  8. import java.security.InvalidKeyException;   
  9. import java.security.Key;   
  10. import java.security.NoSuchAlgorithmException;   
  11. import java.security.SecureRandom;   
  12. import java.security.Security;   
  13. import java.security.spec.InvalidKeySpecException;   
  14. import javax.crypto.Cipher;   
  15. import javax.crypto.KeyGenerator;   
  16. import javax.crypto.SecretKeyFactory;   
  17. import javax.crypto.spec.DESKeySpec;   
  18. import org.apache.commons.configuration.ConfigurationException;   
  19. import org.apache.commons.configuration.PropertiesConfiguration;   
  20. import com.sun.crypto.provider.SunJCE;   
  21.   
  22. public class DESTest {   
  23.     private static final String ALGORITHM = "DES";   
  24.   
  25.     /**  
  26.      * 获得DES加密的密钥。在交易处理的过程中应该定时更 换密钥。需要JCE的支持,如果jdk版本低于1.4,则需要  
  27.      * 安装jce-1_2_2才能正常使用。  
  28.      *   
  29.      * @return Key 返回对称密钥  
  30.      * @throws java.security.NoSuchAlgorithmException  
  31.      * @see util.EncryptUtil 其中包括加密和解密的方法  
  32.      */  
  33.     public Key generateKey() throws EncryptException {   
  34.         try {   
  35.             Security.insertProviderAt(new SunJCE(), 1);   
  36.             KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);   
  37.             generator.init(new SecureRandom());   
  38.             Key key = generator.generateKey();   
  39.             return key;   
  40.         } catch (NoSuchAlgorithmException e) {   
  41.             throw new EncryptException(e);   
  42.         }   
  43.     }   
  44.   
  45.     /**  
  46.      * 得到一个密钥的密码  
  47.      *   
  48.      * @param key  
  49.      *            密钥  
  50.      * @param cipherMode  
  51.      *            密码的类型  
  52.      * @return Cipher  
  53.      * @throws util.EncryptException  
  54.      *             当加密出现异常情况时,产生异常信息  
  55.      */  
  56.     public Cipher getCipher(Key key, int cipherMode) throws EncryptException {   
  57.         try {   
  58.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   
  59.             cipher.init(cipherMode, key);   
  60.             return cipher;   
  61.         } catch (Exception e) {   
  62.             // e.printStackTrace();   
  63.             throw new EncryptException("Generate Cipher occurs Exception.["  
  64.                     + e.getMessage() + "]");   
  65.         }   
  66.     }   
  67.   
  68.     public void saveKey(Key key, String filename) throws EncryptException {   
  69.         if (key == null) {   
  70.             return;   
  71.         }   
  72.   
  73.         File file = new File(filename);   
  74.         try {   
  75.             file.createNewFile();   
  76.         } catch (IOException e1) {   
  77.             throw new EncryptException(e1);   
  78.         }   
  79.   
  80.         try {   
  81.             PropertiesConfiguration publicConfig = new PropertiesConfiguration(   
  82.                     filename);   
  83.             publicConfig.setProperty("Key", Utils.bytesToHexStr(key   
  84.                     .getEncoded()));   
  85.             publicConfig.save();   
  86.         } catch (ConfigurationException e) {   
  87.             throw new EncryptException(e);   
  88.         }   
  89.     }   
  90.   
  91.     public Key loadKey(String filename) throws EncryptException {   
  92.         try {   
  93.             PropertiesConfiguration config = new PropertiesConfiguration(   
  94.                     new File(filename));   
  95.             String privateKeyValue = config.getString("Key");   
  96.             // 从原始密钥数据创建DESKeySpec对象   
  97.             DESKeySpec dks = new DESKeySpec(Utils   
  98.                     .hexStrToBytes(privateKeyValue));   
  99.             // 创建一个密钥工厂,然后用它把DESKeySpec转换成Secret Key对象   
  100.             SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");   
  101.             Key key = keyFactory.generateSecret(dks);   
  102.             return key;   
  103.         } catch (ConfigurationException e) {   
  104.             throw new EncryptException(e);   
  105.         } catch (NoSuchAlgorithmException e) {   
  106.             throw new EncryptException(e);   
  107.         } catch (InvalidKeyException e) {   
  108.             throw new EncryptException(e);   
  109.         } catch (InvalidKeySpecException e) {   
  110.             throw new EncryptException(e);   
  111.         }   
  112.     }   
  113.   
  114.     public byte[] doEncrypt(Key key, byte[] data) throws EncryptException {   
  115.         try {   
  116.             // Get a cipher object   
  117.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   
  118.   
  119.             // Encrypt   
  120.             cipher.init(Cipher.ENCRYPT_MODE, key);   
  121.             // byte[] stringBytes = amalgam.getBytes("UTF8");   
  122.             byte[] raw = cipher.doFinal(data);   
  123.             // BASE64Encoder encoder = new BASE64Encoder();   
  124.             // String base64 = encoder.encode(raw);   
  125.             return raw;   
  126.         } catch (Exception e) {   
  127.             e.printStackTrace();   
  128.             throw new EncryptException("Do encrypt occurs Exception.["  
  129.                     + e.getMessage() + "]");   
  130.         }   
  131.     }   
  132.   
  133.     public byte[] doDecrypt(Key key, byte[] raw) throws EncryptException {   
  134.         try {   
  135.             // Get a cipher object   
  136.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   
  137.             // Decrypt   
  138.             cipher.init(Cipher.DECRYPT_MODE, key);   
  139.             // BASE64Decoder decoder = new BASE64Decoder();   
  140.             // byte[] raw = decoder.decodeBuffer(data);   
  141.             byte[] data = cipher.doFinal(raw);   
  142.             // String result = new String(stringBytes, "UTF8");   
  143.             // System.out.println("the decrypted data is: " + result);   
  144.             return data;   
  145.         } catch (Exception e) {   
  146.             e.printStackTrace();   
  147.             throw new EncryptException("Do decrypt occurs Exception.["  
  148.                     + e.getMessage() + "]");   
  149.         }   
  150.     }   
  151.   
  152.     public static void main(String[] args) {   
  153.         DESTest bean = new DESTest();   
  154.         String keyFilename = "d:/key.txt";   
  155.         String srcFilename = "d:/temp/1.txt";   
  156.         String encryptFilename = "D:/temp/encrypt_result.dat";   
  157.         String decryptFilename = "D:/temp/decrypt_result.txt";   
  158.   
  159.         Key key = bean.initKey(keyFilename);   
  160.         DESEncrypt encrypt = DESEncryptImpl.getInstance();   
  161.   
  162.         try {   
  163.             // encrypt   
  164.             System.out.println("encrypt begin ...");   
  165.             FileInputStream in = new FileInputStream(srcFilename);   
  166.             ByteArrayOutputStream bout = new ByteArrayOutputStream();   
  167.             byte[] tmpbuf = new byte[1024];   
  168.             int count = 0;   
  169.             while ((count = in.read(tmpbuf)) != -1) {   
  170.                 bout.write(tmpbuf, 0, count);   
  171.                 tmpbuf = new byte[1024];   
  172.             }   
  173.             in.close();   
  174.             byte[] orgData = bout.toByteArray();   
  175.             byte[] raw = encrypt.doEncrypt(key, orgData);   
  176.   
  177.             OutputStream out = new FileOutputStream(new File(encryptFilename));   
  178.             out.write(raw);   
  179.             out.close();   
  180.             System.out.println("encrypt done ...");   
  181.   
  182.             // decrypt   
  183.             System.out.println("decrypt begin ...");   
  184.             in = new FileInputStream(encryptFilename);   
  185.             bout = new ByteArrayOutputStream();   
  186.             tmpbuf = new byte[1024];   
  187.             count = 0;   
  188.             while ((count = in.read(tmpbuf)) != -1) {   
  189.                 bout.write(tmpbuf, 0, count);   
  190.                 tmpbuf = new byte[1024];   
  191.             }   
  192.             in.close();   
  193.             orgData = bout.toByteArray();   
  194.             byte[] data = encrypt.doDecrypt(key, orgData);   
  195.             out = new FileOutputStream(new File(decryptFilename));   
  196.             out.write(data);   
  197.             out.flush();   
  198.             out.close();   
  199.             System.out.println("decrypt done ...");   
  200.         } catch (FileNotFoundException e) {   
  201.             e.printStackTrace();   
  202.         } catch (IOException e) {   
  203.             e.printStackTrace();   
  204.         } catch (EncryptException e) {   
  205.             e.printStackTrace();   
  206.         }   
  207.     }   
  208.   
  209.     /*  
  210.      * test  
  211.      */  
  212.     public Key initKey(String keyFilename) {   
  213.         DESControl control = DESControlImpl.getInstance();   
  214.         File keyFile = new File(keyFilename);   
  215.         Key key = null;   
  216.         try {   
  217.             if (!keyFile.exists()) {   
  218.                 System.out.println("generate Key.");   
  219.                 key = control.generateKey();   
  220.                 control.saveKey(key, keyFilename);   
  221.                 return key;   
  222.   
  223.             } else {   
  224.                 System.out.println("load Key.");   
  225.                 key = control.loadKey(keyFilename);   
  226.                 return key;   
  227.             }   
  228.         } catch (EncryptException e) {   
  229.             e.printStackTrace();   
  230.         }   
  231.         return key;   
  232.     }   
  233. }   
分享到:
评论
1 楼 hywill 2010-04-14  
您好,我最近在做文件压缩加密的功能,请问密钥从哪儿获取呢?
key.txt里面是什么?还望您的指教

相关推荐

Global site tag (gtag.js) - Google Analytics