加密解密整理

来源:互联网 发布:电子商务网络培训 编辑:程序博客网 时间:2024/05/22 04:37
 ===================================================================
MD5加密算法:
Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。该算法的文件号为RFC 1321(R.Rivest,MIT Laboratory for Computer Science and RSA Data Security Inc. April 1992)
Java代码
public final class MD5Crypt {   
  1.   
  2. /**  
  3. *  
  4. * Command line test rig.  
  5.  * @throws NoSuchAlgorithmException   
  6. *  
  7. */  
  8.   
  9. static public void main(String argv[]) throws NoSuchAlgorithmException   
  10. {   
  11.     System.out.println(crypt("daliantan0v0"));;   
  12. // if ((argv.length < 1) || (argv.length > 2))  
  13. //   {   
  14. //  System.err.println("Usage: MD5Crypt password salt");  
  15. //  System.exit(1);   
  16. //   }   
  17. //   
  18. // if (argv.length == 2)   
  19. //   {   
  20. //  System.err.println(MD5Crypt.crypt(argv[0], argv[1]));  
  21. //   }   
  22. // else   
  23. //   {   
  24. //  System.err.println(MD5Crypt.crypt(argv[0]));  
  25. //   }   
  26. //    
  27. // System.exit(0);   
  28. }   
  29.   
  30. static private final String SALTCHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";   
  31.   
  32. static private final String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   
  33.   
  34. static private final String to64(long v, int size)   
  35. {   
  36.  StringBuffer result = new StringBuffer();   
  37.   
  38.  while (--size >= 0)   
  39.    {   
  40.     result.append(itoa64.charAt((int) (v & 0x3f)));   
  41.     v >>>= 6;   
  42.    }   
  43.   
  44.  return result.toString();   
  45. }   
  46.   
  47. static private final void clearbits(byte bits[])   
  48. {   
  49.  for (int i = 0; i < bits.length; i++)   
  50.    {   
  51.     bits[i] = 0;   
  52.    }   
  53. }   
  54.   
  55.   
  56.   
  57. /**  
  58. * convert an encoded unsigned byte value into a int 
  59. * with the unsigned value.  
  60. */  
  61.   
  62. static private final int bytes2u(byte inp)   
  63. {   
  64.  return (int) inp & 0xff;   
  65. }   
  66.   
  67. /**  
  68. * <p>This method actually generates a OpenBSD/FreeBSD/Linux PAM compatible 
  69. * md5-encoded password hash from a plaintext password and a 
  70. * salt.</p>  
  71. *  
  72. * <p>The resulting string will be in the form '$1$&lt;salt&gt;$&lt;hashed mess&gt;</p> 
  73. *  
  74. * @param password Plaintext password  
  75. *  
  76. * @return An OpenBSD/FreeBSD/Linux-compatible md5-hashed password field. 
  77.  * @throws NoSuchAlgorithmException   
  78. */  
  79.   
  80. static public final String crypt(String password) throws NoSuchAlgorithmException   
  81. {   
  82.  StringBuffer salt = new StringBuffer();   
  83.  java.util.Random randgen = new java.util.Random();   
  84.   
  85.  /* -- */  
  86.   
  87.   while (salt.length() < 8)   
  88.     {   
  89.      int index = (int) (randgen.nextFloat() * SALTCHARS.length());   
  90.       salt.append(SALTCHARS.substring(index, index+1));   
  91.     }   
  92.   
  93.   return MD5Crypt.crypt(password, salt.toString());   
  94. }   
  95.   
  96. /**  
  97. * <p>This method actually generates a OpenBSD/FreeBSD/Linux PAM compatible 
  98. * md5-encoded password hash from a plaintext password and a 
  99. * salt.</p>  
  100. *  
  101. * <p>The resulting string will be in the form '$1$&lt;salt&gt;$&lt;hashed mess&gt;</p> 
  102. *  
  103. * @param password Plaintext password  
  104. * @param salt A short string to use to randomize md5.  May start with $1$, which 
  105. *             will be ignored.  It is explicitly permitted to pass a pre-existing 
  106. *             MD5Crypt'ed password entry as the salt.  crypt() will strip the salt 
  107. *             chars out properly.  
  108. *  
  109. * @return An OpenBSD/FreeBSD/Linux-compatible md5-hashed password field. 
  110.  * @throws NoSuchAlgorithmException   
  111. */  
  112.   
  113. static public final String crypt(String password, String salt) throws NoSuchAlgorithmException   
  114. {   
  115.  /* This string is magic for this algorithm.  Having it this way, 
  116.   * we can get get better later on */  
  117.   
  118.  String magic = "$1$";   
  119.  byte finalState[];   
  120.  MessageDigest ctx, ctx1;   
  121.  long l;   
  122.   
  123.  /* -- */  
  124.   
  125.  /* Refine the Salt first */  
  126.   
  127.  /* If it starts with the magic string, then skip that */  
  128.     
  129.  if (salt.startsWith(magic))   
  130.    {   
  131.     salt = salt.substring(magic.length());   
  132.    }   
  133.   
  134.  /* It stops at the first '$', max 8 chars */  
  135.   
  136.  if (salt.indexOf('$') != -1)   
  137.    {   
  138.     salt = salt.substring(0, salt.indexOf('$'));   
  139.    }   
  140.   
  141.  if (salt.length() > 8)   
  142.    {   
  143.     salt = salt.substring(08);   
  144.    }   
  145.   
  146.  ctx = MessageDigest.getInstance("MD5");   
  147.   
  148.  ctx.update(password.getBytes());    // The password first, since that is what is most unknown  
  149.  ctx.update(magic.getBytes());    // Then our magic string  
  150.  ctx.update(salt.getBytes());    // Then the raw salt  
  151.   
  152.  /* Then just as many characters of the MD5(pw,salt,pw) */  
  153.   
  154.  ctx1 = MessageDigest.getInstance("MD5");   
  155.  ctx1.update(password.getBytes());   
  156.  ctx1.update(salt.getBytes());   
  157.  ctx1.update(password.getBytes());   
  158.  finalState = ctx1.digest();   
  159.   
  160.  for (int pl = password.length(); pl > 0; pl -= 16)   
  161.    {   
  162.     forint i=0; i< (pl > 16 ? 16 : pl); i++ )   
  163.       ctx.update(finalState[i] );   
  164.    }   
  165.   
  166.  /* the original code claimed that finalState was being cleared 
  167.     to keep dangerous bits out of memory, but doing this is also 
  168.     required in order to get the right output. */  
  169.   
  170.  clearbits(finalState);   
  171.     
  172.  /* Then something really weird... */  
  173.   
  174.  for (int i = password.length(); i != 0; i >>>=1)   
  175.    {   
  176.     if ((i & 1) != 0)   
  177.       {   
  178.         ctx.update(finalState[0]);   
  179.       }   
  180.     else  
  181.       {   
  182.         ctx.update(password.getBytes()[0]);   
  183.       }   
  184.    }   
  185.   
  186.  finalState = ctx.digest();   
  187.   
  188.  /*  
  189.   * and now, just to make sure things don't run too fast 
  190.   * On a 60 Mhz Pentium this takes 34 msec, so you would 
  191.   * need 30 seconds to build a 1000 entry dictionary... 
  192.   *  
  193.   * (The above timings from the C version)  
  194.   */  
  195.   
  196.  for (int i = 0; i < 1000; i++)   
  197.    {   
  198.     ctx1 = MessageDigest.getInstance("MD5");   
  199.   
  200.     if ((i & 1) != 0)   
  201.       {   
  202.         ctx1.update(password.getBytes());   
  203.       }   
  204.     else  
  205.       {   
  206.         forint c=0; c<16; c++ )   
  207.           ctx1.update(finalState[c]);   
  208.       }   
  209.   
  210.     if ((i % 3) != 0)   
  211.       {   
  212.         ctx1.update(salt.getBytes());   
  213.       }   
  214.   
  215.     if ((i % 7) != 0)   
  216.       {   
  217.         ctx1.update(password.getBytes());   
  218.       }   
  219.   
  220.     if ((i & 1) != 0)   
  221.       {   
  222.         forint c=0; c<16; c++ )   
  223.           ctx1.update(finalState[c]);   
  224.       }   
  225.     else  
  226.       {   
  227.         ctx1.update(password.getBytes());   
  228.       }   
  229.   
  230.     finalState = ctx1.digest();   
  231.    }   
  232.   
  233.  /* Now make the output string */  
  234.   
  235.  StringBuffer result = new StringBuffer();   
  236.   
  237.  result.append(magic);   
  238.  result.append(salt);   
  239.  result.append("$");   
  240.   
  241.  l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]);   
  242.  result.append(to64(l, 4));   
  243.   
  244.  l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]);   
  245.  result.append(to64(l, 4));   
  246.   
  247.  l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]);   
  248.  result.append(to64(l, 4));   
  249.   
  250.  l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]);   
  251.  result.append(to64(l, 4));   
  252.   
  253.  l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]);   
  254.  result.append(to64(l, 4));   
  255.   
  256.  l = bytes2u(finalState[11]);   
  257.  result.append(to64(l, 2));   
  258.   
  259.  /* Don't leave anything around in vm they could use. */  
  260.  clearbits(finalState);   
  261.   
  262.  return result.toString();   
  263. }   
  264. }  

DES加密与解密:
Java代码 复制代码 收藏代码
  1. /**    
  2.  *     
  3.  * 使用DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储.   
  4.  *     
  5.  * 方法: void getKey(String strKey)从strKey的字条生成一个Key   
  6.  *     
  7.  * String getEncString(String strMing)对strMing进行加密,返回String密文 String   
  8.  * getDesString(String strMi)对strMin进行解密,返回String明文   
  9.  *     
  10.  * byte[] getEncCode(byte[] byteS)byte[]型的加密 byte[] getDesCode(byte[]   
  11.  * byteD)byte[]型的解密    
  12.  */     
  13.      
  14. public class ThreeDES {      
  15.     Key key;      
  16.      
  17.     /**    
  18.      * 根据参数生成KEY    
  19.      *     
  20.      * @param strKey    
  21.      */     
  22.     public void getKey(String strKey) {      
  23.         try {      
  24.             KeyGenerator _generator = KeyGenerator.getInstance("DES");      
  25.             _generator.init(new SecureRandom(strKey.getBytes()));      
  26.             this.key = _generator.generateKey();    
  27.             _generator = null;      
  28.         } catch (Exception e) {      
  29.             e.printStackTrace();      
  30.         }      
  31.     }      
  32.      
  33.     /**    
  34.      * 加密String明文输入,String密文输出    
  35.      *     
  36.      * @param strMing    
  37.      * @return    
  38.      */     
  39.     public String getEncString(String strMing) {      
  40.         byte[] byteMi = null;      
  41.         byte[] byteMing = null;      
  42.         String strMi = "";      
  43.         BASE64Encoder base64en = new BASE64Encoder();      
  44.         try {      
  45.             byteMing = strMing.getBytes("UTF8");      
  46.             byteMi = this.getEncCode(byteMing);      
  47.             strMi = base64en.encode(byteMi);      
  48.         } catch (Exception e) {      
  49.             e.printStackTrace();      
  50.         } finally {      
  51.             base64en = null;      
  52.             byteMing = null;      
  53.             byteMi = null;      
  54.         }      
  55.         return strMi;      
  56.     }      
  57.      
  58.     /**    
  59.      * 解密 以String密文输入,String明文输出    
  60.      *     
  61.      * @param strMi    
  62.      * @return    
  63.      */     
  64.     public String getDesString(String strMi) {      
  65.         BASE64Decoder base64De = new BASE64Decoder();      
  66.         byte[] byteMing = null;      
  67.         byte[] byteMi = null;      
  68.         String strMing = "";      
  69.         try {      
  70.             byteMi = base64De.decodeBuffer(strMi);      
  71.             byteMing = this.getDesCode(byteMi);      
  72.             strMing = new String(byteMing, "UTF8");      
  73.         } catch (Exception e) {      
  74.             e.printStackTrace();      
  75.         } finally {      
  76.             base64De = null;      
  77.             byteMing = null;      
  78.             byteMi = null;      
  79.         }      
  80.         return strMing;      
  81.     }      
  82.      
  83.     /**    
  84.      * 加密以byte[]明文输入,byte[]密文输出    
  85.      *     
  86.      * @param byteS    
  87.      * @return    
  88.      */     
  89.     private byte[] getEncCode(byte[] byteS) {      
  90.         byte[] byteFina = null;      
  91.         Cipher cipher;      
  92.         try {      
  93.             cipher = Cipher.getInstance("DES");      
  94.             cipher.init(Cipher.ENCRYPT_MODE, key);      
  95.             byteFina = cipher.doFinal(byteS);      
  96.         } catch (Exception e) {      
  97.             e.printStackTrace();      
  98.         } finally {      
  99.             cipher = null;      
  100.         }      
  101.         return byteFina;      
  102.     }      
  103.      
  104.     /**    
  105.      * 解密以byte[]密文输入,以byte[]明文输出    
  106.      *     
  107.      * @param byteD    
  108.      * @return    
  109.      */     
  110.     private byte[] getDesCode(byte[] byteD) {      
  111.         Cipher cipher;      
  112.         byte[] byteFina = null;      
  113.         try {      
  114.             cipher = Cipher.getInstance("DES");      
  115.             cipher.init(Cipher.DECRYPT_MODE, key);      
  116.             byteFina = cipher.doFinal(byteD);      
  117.         } catch (Exception e) {      
  118.             e.printStackTrace();      
  119.         } finally {      
  120.             cipher = null;      
  121.         }      
  122.         return byteFina;      
  123.      
  124.     }      
  125.      
  126.     public static void main(String[] args) {      
  127.         ThreeDES des = new ThreeDES();// 实例化一个对像     
  128.         des.getKey("daliantan0v0");// 生成密匙     
  129.            
  130.         String strEnc = des.getEncString("ss = 00-13-77-5A-B2-F4=2010-10-10");// 加密字符串,返回String的密文     
  131.         System.out.println(strEnc);      
  132.      
  133.         String strDes = des.getDesString("d6LhO6+II12wjY+JzushFtC4II8wVDOI");// 把String 类型的密文解密      
  134.         System.out.println(strDes);      
  135.     }      
  136.      
  137. }    

RSA加密解密:
  RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。 RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。
Java代码 复制代码 收藏代码
  1. public class RSAEncrypt {      
  2.      
  3.     public static void main(String[] args) {      
  4.         try {      
  5.                   
  6.             RSAEncrypt encrypt = new RSAEncrypt();      
  7.             String encryptText = "ganlisxn1104";      
  8.             KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");      
  9.             keyPairGen.initialize(1024);      
  10.             KeyPair keyPair = keyPairGen.generateKeyPair();      
  11.             // Generate keys      
  12.                   
  13.             RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();      
  14.             RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();      
  15.                   
  16.             byte[] e = encrypt.encrypt(publicKey,encryptText.getBytes());      
  17.                   
  18.             byte[] de = encrypt.decrypt(privateKey, e);      
  19.                   
  20.             System.out.println("加密:"+encrypt.bytesToString(e));      
  21.                   
  22.             System.out.println("解密:"+encrypt.bytesToString(de));      
  23.               
  24.         } catch (Exception e) {      
  25.             e.printStackTrace();      
  26.         }      
  27.     }      
  28.   public void doDecrypt(String encryptText) throws NoSuchAlgorithmException{   
  29.        RSAEncrypt encrypt = new RSAEncrypt();      
  30.        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");     
  31.        keyPairGen.initialize(1024);      
  32.        KeyPair keyPair = keyPairGen.generateKeyPair();      
  33.        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();      
  34.        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();      
  35.              
  36.       // byte[] e = ' &r? ????gf??¦?_???(?)Z!-Dl?tA/??rl???`l???????iR?"|$?;D?I???|?F?JH???h???S?)u-?H??"`?M?2?#¢]?¬?6r?(??Y??:? b ';  
  37.            //encrypt.encrypt(publicKey,encryptText.getBytes());     
  38.              
  39.        byte[] de = encrypt.decrypt(privateKey, encryptText.getBytes());      
  40.              
  41.       // System.out.println("加密:"+encrypt.bytesToString(e));     
  42.           System.out.println("11111111111111");   
  43.        System.out.println("解密:"+encrypt.bytesToString(de));    
  44.   }   
  45.     /** */     
  46.     /**    
  47.      * Change byte array to String.    
  48.      *     
  49.      * @return byte[]    
  50.      */     
  51.     protected String bytesToString(byte[] encrytpByte) {      
  52.         String result = "";      
  53.         for (Byte bytes : encrytpByte) {      
  54.             result += (char) bytes.intValue();      
  55.         }      
  56.         return result;      
  57.     }      
  58.      
  59.     /** */     
  60.     /**    
  61.      * Encrypt String.    
  62.      *     
  63.      * @return byte[]    
  64.      */     
  65.     protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {      
  66.         if (publicKey != null) {      
  67.             try {      
  68.                 Cipher cipher = Cipher.getInstance("RSA");      
  69.                 cipher.init(Cipher.ENCRYPT_MODE, publicKey);      
  70.                 return cipher.doFinal(obj);      
  71.             } catch (Exception e) {      
  72.                 e.printStackTrace();      
  73.             }      
  74.         }      
  75.         return null;      
  76.     }      
  77.      
  78.     /** */     
  79.     /**    
  80.      * Basic decrypt method    
  81.      *     
  82.      * @return byte[]    
  83.      */     
  84.     protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {      
  85.         if (privateKey != null) {      
  86.             try {      
  87.                 Cipher cipher = Cipher.getInstance("RSA");      
  88.                 cipher.init(Cipher.DECRYPT_MODE, privateKey);      
  89.                 return cipher.doFinal(obj);      
  90.             } catch (Exception e) {      
  91.                 e.printStackTrace();      
  92.             }      
  93.         }      
  94.         return null;      
  95.     }      
  96. }  

DES加密
数据加密算法(Data Encryption Algorithm,DEA)的数据加密标准(Data Encryption Standard,DES)是规范的描述,它出自IBM 的研究工作,并在 1977 年被美国政府正式采纳。它很可能是使用最广泛的密钥系统,特别是在保护金融数据的安全中,最初开发的 DES 是嵌入硬 件中的。通常,自动取款机(Automated Teller Machine,ATM)都使用 DES。

安全散列算法SHA
  (Secure Hash Algorithm,SHA)
  是美国国家标准和技术局发布的国家标准FIPS PUB 180-1,一般称为SHA-1。其对长度不超过264二进制位的消息产生160位的消息摘要输出,按512比特块处理其输入。
  SHA是一种数据加密算法,该算法经过加密专家多年来的发展和改进已日益完善,现在已成为公认的最安全的散列算法之一,并被广泛使用。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。散列函数值可以说时对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。

Java代码 复制代码 收藏代码
  1. /**    
  2.  * 加密解密    
  3.  *     
  4.  * @author shy.qiu    
  5.  * @since  http://blog.csdn.net/qiushyfm    
  6.  */     
  7. public class Crypt {      
  8.        /**    
  9.      * 进行SHA加密    
  10.      *     
  11.      * @param info    
  12.      *            要加密的信息    
  13.      * @return String 加密后的字符串    
  14.      */     
  15.     public String encryptToSHA(String info) {      
  16.         byte[] digesta = null;      
  17.         try {      
  18.             // 得到一个SHA-1的消息摘要      
  19.             MessageDigest alga = MessageDigest.getInstance("SHA-1");      
  20.             // 添加要进行计算摘要的信息      
  21.             alga.update(info.getBytes());      
  22.             // 得到该摘要      
  23.             digesta = alga.digest();      
  24.         } catch (NoSuchAlgorithmException e) {      
  25.             e.printStackTrace();      
  26.         }      
  27.         // 将摘要转为字符串      
  28.         String rs = byte2hex(digesta);      
  29.         return rs;      
  30.     }      
  31.     // //////////////////////////////////////////////////////////////////////////     
  32.     /**    
  33.      * 创建密匙    
  34.      *     
  35.      * @param algorithm    
  36.      *            加密算法,可用 DES,DESede,Blowfish    
  37.      * @return SecretKey 秘密(对称)密钥    
  38.      */     
  39.     public SecretKey createSecretKey(String algorithm) {      
  40.         // 声明KeyGenerator对象      
  41.         KeyGenerator keygen;      
  42.         // 声明 密钥对象      
  43.         SecretKey deskey = null;      
  44.         try {      
  45.             // 返回生成指定算法的秘密密钥的 KeyGenerator 对象     
  46.             keygen = KeyGenerator.getInstance(algorithm);      
  47.             // 生成一个密钥      
  48.             deskey = keygen.generateKey();      
  49.         } catch (NoSuchAlgorithmException e) {      
  50.             e.printStackTrace();      
  51.         }      
  52.         // 返回密匙      
  53.         return deskey;      
  54.     }      
  55.     /**    
  56.      * 根据密匙进行DES加密    
  57.      *     
  58.      * @param key    
  59.      *            密匙    
  60.      * @param info    
  61.      *            要加密的信息    
  62.      * @return String 加密后的信息    
  63.      */     
  64.     public String encryptToDES(SecretKey key, String info) {      
  65.         // 定义 加密算法,可用 DES,DESede,Blowfish     
  66.         String Algorithm = "DES";      
  67.         // 加密随机数生成器 (RNG),(可以不写)      
  68.         SecureRandom sr = new SecureRandom();      
  69.         // 定义要生成的密文      
  70.         byte[] cipherByte = null;      
  71.         try {      
  72.             // 得到加密/解密器      
  73.             Cipher c1 = Cipher.getInstance(Algorithm);      
  74.             // 用指定的密钥和模式初始化Cipher对象      
  75.             // 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)     
  76.             c1.init(Cipher.ENCRYPT_MODE, key, sr);      
  77.             // 对要加密的内容进行编码处理,      
  78.             cipherByte = c1.doFinal(info.getBytes());      
  79.         } catch (Exception e) {      
  80.             e.printStackTrace();      
  81.         }      
  82.         // 返回密文的十六进制形式      
  83.         return byte2hex(cipherByte);      
  84.     }      
  85.     /**    
  86.      * 根据密匙进行DES解密    
  87.      *     
  88.      * @param key    
  89.      *            密匙    
  90.      * @param sInfo    
  91.      *            要解密的密文    
  92.      * @return String 返回解密后信息    
  93.      */     
  94.     public String decryptByDES(SecretKey key, String sInfo) {      
  95.         // 定义 加密算法,      
  96.         String Algorithm = "DES";      
  97.         // 加密随机数生成器 (RNG)      
  98.         SecureRandom sr = new SecureRandom();      
  99.         byte[] cipherByte = null;      
  100.         try {      
  101.             // 得到加密/解密器      
  102.             Cipher c1 = Cipher.getInstance(Algorithm);      
  103.             // 用指定的密钥和模式初始化Cipher对象      
  104.             c1.init(Cipher.DECRYPT_MODE, key, sr);      
  105.             // 对要解密的内容进行编码处理      
  106.             cipherByte = c1.doFinal(hex2byte(sInfo));      
  107.         } catch (Exception e) {      
  108.             e.printStackTrace();      
  109.         }      
  110.         // return byte2hex(cipherByte);     
  111.         return new String(cipherByte);      
  112.     }      
  113.     // /////////////////////////////////////////////////////////////////////////////     
  114.     /**    
  115.      * 创建密匙组,并将公匙,私匙放入到指定文件中    
  116.      *     
  117.      * 默认放入mykeys.bat文件中    
  118.      * @throws IOException   
  119.      */     
  120.     public void createPairKey() throws IOException {      
  121.         try {      
  122.             // 根据特定的算法一个密钥对生成器      
  123.             KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");      
  124.             // 加密随机数生成器 (RNG)      
  125.             SecureRandom random = new SecureRandom();      
  126.             // 重新设置此随机对象的种子      
  127.             random.setSeed(1000);      
  128.             // 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器     
  129.             keygen.initialize(512, random);// keygen.initialize(512);     
  130.             // 生成密钥组      
  131.             KeyPair keys = keygen.generateKeyPair();      
  132.             // 得到公匙      
  133.             PublicKey pubkey = keys.getPublic();      
  134.             // 得到私匙      
  135.             PrivateKey prikey = keys.getPrivate();    
  136.             //取得公司名称,写入公钥中   
  137.             GetProperties gp = new GetProperties();   
  138.             String company = gp.getCompany();   
  139.             // 将公匙私匙写入到文件当中      
  140.             doObjToFile("mykeys.bat"new Object[] { prikey, pubkey ,company});      
  141.         } catch (NoSuchAlgorithmException e) {      
  142.             e.printStackTrace();      
  143.         }      
  144.     }      
  145.     /**    
  146.      * 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中    
  147.      *     
  148.      * @param info    
  149.      *            要签名的信息    
  150.      * @param signfile    
  151.      *            存入的文件    
  152.      */     
  153.     public void signToInfo(String info, String signfile) {      
  154.         // 从文件当中读取私匙      
  155.         PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat"1);      
  156.         // 从文件中读取公匙      
  157.         PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat"2);    
  158.         String in = (String) getObjFromFile("mykeys.bat"3);   
  159.         System.out.println("****"+in);   
  160.         try {      
  161.             // Signature 对象可用来生成和验证数字签名     
  162.             Signature signet = Signature.getInstance("DSA");      
  163.             // 初始化签署签名的私钥      
  164.             signet.initSign(myprikey);      
  165.             // 更新要由字节签名或验证的数据      
  166.             signet.update(info.getBytes());      
  167.             // 签署或验证所有更新字节的签名,返回签名      
  168.             byte[] signed = signet.sign();      
  169.             // 将数字签名,公匙,信息放入文件中      
  170.             doObjToFile("d:\\"+signfile, new Object[] { signed, mypubkey, info ,in});      
  171.         } catch (Exception e) {      
  172.             e.printStackTrace();      
  173.         }      
  174.     }      
  175.     /**    
  176.      * 读取数字签名文件 根据公匙,签名,信息验证信息的合法性    
  177.      *     
  178.      * @return true 验证成功 false 验证失败    
  179.      */     
  180.     public boolean validateSign(String signfile) {      
  181.         // 读取公匙      
  182.         PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);    
  183.         System.out.println("mypubkey==="+mypubkey);   
  184.         // 读取签名      
  185.         byte[] signed = (byte[]) getObjFromFile(signfile, 1);      
  186.         // 读取信息      
  187.         String info = (String) getObjFromFile(signfile, 3);    
  188.         System.out.println("info==="+info);   
  189.         try {      
  190.             // 初始一个Signature对象,并用公钥和签名进行验证     
  191.             Signature signetcheck = Signature.getInstance("DSA");      
  192.             // 初始化验证签名的公钥      
  193.             signetcheck.initVerify(mypubkey);      
  194.             // 使用指定的 byte 数组更新要签名或验证的数据     
  195.             signetcheck.update(info.getBytes());        
  196.             // 验证传入的签名      
  197.             return signetcheck.verify(signed);      
  198.         } catch (Exception e) {      
  199.             e.printStackTrace();      
  200.             return false;      
  201.         }      
  202.     }      
  203.     /**    
  204.      * 将二进制转化为16进制字符串    
  205.      *     
  206.      * @param b    
  207.      *            二进制字节数组    
  208.      * @return String    
  209.      */     
  210.     public String byte2hex(byte[] b) {      
  211.         String hs = "";      
  212.         String stmp = "";      
  213.         for (int n = 0; n < b.length; n++) {      
  214.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));      
  215.             if (stmp.length() == 1) {      
  216.                 hs = hs + "0" + stmp;      
  217.             } else {      
  218.                 hs = hs + stmp;      
  219.             }      
  220.         }      
  221.         return hs.toUpperCase();      
  222.     }      
  223.     /**    
  224.      * 十六进制字符串转化为2进制    
  225.      *     
  226.      * @param hex    
  227.      * @return    
  228.      */     
  229.     public byte[] hex2byte(String hex) {      
  230.         byte[] ret = new byte[8];      
  231.         byte[] tmp = hex.getBytes();      
  232.         for (int i = 0; i < 8; i++) {      
  233.             ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);      
  234.         }      
  235.         return ret;      
  236.     }      
  237.     /**    
  238.      * 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF    
  239.      *     
  240.      * @param src0    
  241.      *            byte    
  242.      * @param src1    
  243.      *            byte    
  244.      * @return byte    
  245.      */     
  246.     public static byte uniteBytes(byte src0, byte src1) {      
  247.         byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))      
  248.                 .byteValue();      
  249.         _b0 = (byte) (_b0 << 4);      
  250.         byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))      
  251.                 .byteValue();      
  252.         byte ret = (byte) (_b0 ^ _b1);      
  253.         return ret;      
  254.     }      
  255.     /**    
  256.      * 将指定的对象写入指定的文件    
  257.      *     
  258.      * @param file    
  259.      *            指定写入的文件    
  260.      * @param objs    
  261.      *            要写入的对象    
  262.      */     
  263.     public void doObjToFile(String file, Object[] objs) {      
  264.         ObjectOutputStream oos = null;      
  265.         try {      
  266.             FileOutputStream fos = new FileOutputStream(file);      
  267.             oos = new ObjectOutputStream(fos);      
  268.             for (int i = 0; i < objs.length; i++) {      
  269.                 oos.writeObject(objs[i]);      
  270.             }      
  271.         } catch (Exception e) {      
  272.             e.printStackTrace();      
  273.         } finally {      
  274.             try {      
  275.                 oos.close();      
  276.             } catch (IOException e) {      
  277.                 e.printStackTrace();      
  278.             }      
  279.         }      
  280.     }      
  281.     /**    
  282.      * 返回在文件中指定位置的对象    
  283.      *     
  284.      * @param file    
  285.      *            指定的文件    
  286.      * @param i    
  287.      *            从1开始    
  288.      * @return    
  289.      */     
  290.     public Object getObjFromFile(String file, int i) {      
  291.         ObjectInputStream ois = null;      
  292.         Object obj = null;      
  293.         try {      
  294.             FileInputStream fis = new FileInputStream(file);      
  295.             ois = new ObjectInputStream(fis);      
  296.             for (int j = 0; j < i; j++) {      
  297.                 obj = ois.readObject();      
  298.             }      
  299.         } catch (Exception e) {      
  300.             e.printStackTrace();      
  301.         } finally {      
  302.             try {      
  303.                 ois.close();      
  304.             } catch (IOException e) {      
  305.                 e.printStackTrace();      
  306.             }      
  307.         }      
  308.         return obj;      
  309.     }      
  310.     /**    
  311.      * 测试    
  312.      *     
  313.      * @param args    
  314.      * @throws IOException   
  315.      */     
  316.     public static void main(String[] args) throws IOException {      
  317.         Crypt jiami = new Crypt();      
  318.         // 执行MD5加密"Hello world!"      
  319.         System.out.println("Hello经过MD5:" + jiami.encryptToMD5("tanovo"));      
  320.         // 生成一个DES算法的密匙      
  321.         SecretKey key = jiami.createSecretKey("DES");      
  322.         // 用密匙加密信息"Hello world!"      
  323.         String str1 = jiami.encryptToDES(key, "tanovo");      
  324.         System.out.println("使用des加密信息tanovo为:" + str1);      
  325.         // 使用这个密匙解密      
  326.         String str2 = jiami.decryptByDES(key, str1);      
  327.         System.out.println("解密后为:" + str2);      
  328.         // 创建公匙和私匙      
  329.         jiami.createPairKey();      
  330.         // 对Hello world!使用私匙进行签名      
  331.         jiami.signToInfo("Hello""mysign.bat");      
  332.         // 利用公匙对签名进行验证。      
  333.         if (jiami.validateSign("mysign.bat")) {      
  334.             System.out.println("Success!");      
  335.         } else {      
  336.             System.out.println("Fail!");      
  337.         }      
  338.     }      
  339. }    
原创粉丝点击