6820139 发表于 2013-1-16 17:38:03

加密解密整理

MD5加密算法:
Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。该算法的文件号为RFC 1321(R.Rivest,MIT Laboratory for Computer Science and RSA Data Security Inc. April 1992)
public final class MD5Crypt {/**** Command line test rig. * @throws NoSuchAlgorithmException **/static public void main(String argv[]) throws NoSuchAlgorithmException{System.out.println(crypt("daliantan0v0"));;// if ((argv.length < 1) || (argv.length > 2))//   {//System.err.println("Usage: MD5Crypt password salt");//System.exit(1);//   }//// if (argv.length == 2)//   {//System.err.println(MD5Crypt.crypt(argv, argv));//   }// else//   {//System.err.println(MD5Crypt.crypt(argv));//   }// // System.exit(0);}static private final String SALTCHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";static private final String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";static private final String to64(long v, int size){ StringBuffer result = new StringBuffer(); while (--size >= 0)   {result.append(itoa64.charAt((int) (v & 0x3f)));v >>>= 6;   } return result.toString();}static private final void clearbits(byte bits[]){ for (int i = 0; i < bits.length; i++)   {bits = 0;   }}/*** convert an encoded unsigned byte value into a int* with the unsigned value.*/static private final int bytes2u(byte inp){ return (int) inp & 0xff;}/*** <p>This method actually generates a OpenBSD/FreeBSD/Linux PAM compatible* md5-encoded password hash from a plaintext password and a* salt.</p>** <p>The resulting string will be in the form '$1$<salt>$<hashed mess></p>** @param password Plaintext password** @return An OpenBSD/FreeBSD/Linux-compatible md5-hashed password field. * @throws NoSuchAlgorithmException */static public final String crypt(String password) throws NoSuchAlgorithmException{ StringBuffer salt = new StringBuffer(); java.util.Random randgen = new java.util.Random(); /* -- */while (salt.length() < 8)    { int index = (int) (randgen.nextFloat() * SALTCHARS.length());      salt.append(SALTCHARS.substring(index, index+1));    }return MD5Crypt.crypt(password, salt.toString());}/*** <p>This method actually generates a OpenBSD/FreeBSD/Linux PAM compatible* md5-encoded password hash from a plaintext password and a* salt.</p>** <p>The resulting string will be in the form '$1$<salt>$<hashed mess></p>** @param password Plaintext password* @param salt A short string to use to randomize md5.May start with $1$, which*             will be ignored.It is explicitly permitted to pass a pre-existing*             MD5Crypt'ed password entry as the salt.crypt() will strip the salt*             chars out properly.** @return An OpenBSD/FreeBSD/Linux-compatible md5-hashed password field. * @throws NoSuchAlgorithmException */static public final String crypt(String password, String salt) throws NoSuchAlgorithmException{ /* This string is magic for this algorithm.Having it this way,* we can get get better later on */ String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; /* -- */ /* Refine the Salt first */ /* If it starts with the magic string, then skip that */if (salt.startsWith(magic))   {salt = salt.substring(magic.length());   } /* It stops at the first '$', max 8 chars */ if (salt.indexOf('$') != -1)   {salt = salt.substring(0, salt.indexOf('$'));   } if (salt.length() > 8)   {salt = salt.substring(0, 8);   } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes());    // The password first, since that is what is most unknown ctx.update(magic.getBytes());    // Then our magic string ctx.update(salt.getBytes());    // Then the raw salt /* Then just as many characters of the MD5(pw,salt,pw) */ ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16)   {for( int i=0; i< (pl > 16 ? 16 : pl); i++ )ctx.update(finalState );   } /* the original code claimed that finalState was being cleared    to keep dangerous bits out of memory, but doing this is also    required in order to get the right output. */ clearbits(finalState);/* Then something really weird... */ for (int i = password.length(); i != 0; i >>>=1)   {if ((i & 1) != 0){    ctx.update(finalState);}else{    ctx.update(password.getBytes());}   } finalState = ctx.digest(); /** and now, just to make sure things don't run too fast* On a 60 Mhz Pentium this takes 34 msec, so you would* need 30 seconds to build a 1000 entry dictionary...** (The above timings from the C version)*/ for (int i = 0; i < 1000; i++)   {ctx1 = MessageDigest.getInstance("MD5");if ((i & 1) != 0){    ctx1.update(password.getBytes());}else{    for( int c=0; c<16; c++ )      ctx1.update(finalState);}if ((i % 3) != 0){    ctx1.update(salt.getBytes());}if ((i % 7) != 0){    ctx1.update(password.getBytes());}if ((i & 1) != 0){    for( int c=0; c<16; c++ )      ctx1.update(finalState);}else{    ctx1.update(password.getBytes());}finalState = ctx1.digest();   } /* Now make the output string */ StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState) << 16) | (bytes2u(finalState) << 8) | bytes2u(finalState); result.append(to64(l, 4)); l = (bytes2u(finalState) << 16) | (bytes2u(finalState) << 8) | bytes2u(finalState); result.append(to64(l, 4)); l = (bytes2u(finalState) << 16) | (bytes2u(finalState) << 8) | bytes2u(finalState); result.append(to64(l, 4)); l = (bytes2u(finalState) << 16) | (bytes2u(finalState) << 8) | bytes2u(finalState); result.append(to64(l, 4)); l = (bytes2u(finalState) << 16) | (bytes2u(finalState) << 8) | bytes2u(finalState); result.append(to64(l, 4)); l = bytes2u(finalState); result.append(to64(l, 2)); /* Don't leave anything around in vm they could use. */ clearbits(finalState); return result.toString();}}

DES加密与解密:
/**   *    * 使用DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储.   *    * 方法: void getKey(String strKey)从strKey的字条生成一个Key   *    * String getEncString(String strMing)对strMing进行加密,返回String密文 String   * getDesString(String strMi)对strMin进行解密,返回String明文   *    * byte[] getEncCode(byte[] byteS)byte[]型的加密 byte[] getDesCode(byte[]   * byteD)byte[]型的解密   */    public class ThreeDES {       Key key;         /**       * 根据参数生成KEY       *      * @param strKey       */      public void getKey(String strKey) {         try {               KeyGenerator _generator = KeyGenerator.getInstance("DES");               _generator.init(new SecureRandom(strKey.getBytes()));               this.key = _generator.generateKey();             _generator = null;         } catch (Exception e) {               e.printStackTrace();         }       }         /**       * 加密String明文输入,String密文输出       *      * @param strMing       * @return       */      public String getEncString(String strMing) {         byte[] byteMi = null;         byte[] byteMing = null;         String strMi = "";         BASE64Encoder base64en = new BASE64Encoder();         try {               byteMing = strMing.getBytes("UTF8");               byteMi = this.getEncCode(byteMing);               strMi = base64en.encode(byteMi);         } catch (Exception e) {               e.printStackTrace();         } finally {               base64en = null;               byteMing = null;               byteMi = null;         }         return strMi;       }         /**       * 解密 以String密文输入,String明文输出       *      * @param strMi       * @return       */      public String getDesString(String strMi) {         BASE64Decoder base64De = new BASE64Decoder();         byte[] byteMing = null;         byte[] byteMi = null;         String strMing = "";         try {               byteMi = base64De.decodeBuffer(strMi);               byteMing = this.getDesCode(byteMi);               strMing = new String(byteMing, "UTF8");         } catch (Exception e) {               e.printStackTrace();         } finally {               base64De = null;               byteMing = null;               byteMi = null;         }         return strMing;       }         /**       * 加密以byte[]明文输入,byte[]密文输出       *      * @param byteS       * @return       */      private byte[] getEncCode(byte[] byteS) {         byte[] byteFina = null;         Cipher cipher;         try {               cipher = Cipher.getInstance("DES");               cipher.init(Cipher.ENCRYPT_MODE, key);               byteFina = cipher.doFinal(byteS);         } catch (Exception e) {               e.printStackTrace();         } finally {               cipher = null;         }         return byteFina;       }         /**       * 解密以byte[]密文输入,以byte[]明文输出       *      * @param byteD       * @return       */      private byte[] getDesCode(byte[] byteD) {         Cipher cipher;         byte[] byteFina = null;         try {               cipher = Cipher.getInstance("DES");               cipher.init(Cipher.DECRYPT_MODE, key);               byteFina = cipher.doFinal(byteD);         } catch (Exception e) {               e.printStackTrace();         } finally {               cipher = null;         }         return byteFina;         }         public static void main(String[] args) {         ThreeDES des = new ThreeDES();// 实例化一个对像         des.getKey("daliantan0v0");// 生成密匙                   String strEnc = des.getEncString("ss = 00-13-77-5A-B2-F4=2010-10-10");// 加密字符串,返回String的密文         System.out.println(strEnc);             String strDes = des.getDesString("d6LhO6+II12wjY+JzushFtC4II8wVDOI");// 把String 类型的密文解密            System.out.println(strDes);       }   }

RSA加密解密:
  RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。 RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。
public class RSAEncrypt {         public static void main(String[] args) {         try {                              RSAEncrypt encrypt = new RSAEncrypt();               String encryptText = "ganlisxn1104";               KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");               keyPairGen.initialize(1024);               KeyPair keyPair = keyPairGen.generateKeyPair();               // Generate keys                              RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();               RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();                              byte[] e = encrypt.encrypt(publicKey,encryptText.getBytes());                              byte[] de = encrypt.decrypt(privateKey, e);                              System.out.println("加密:"+encrypt.bytesToString(e));                              System.out.println("解密:"+encrypt.bytesToString(de));                      } catch (Exception e) {               e.printStackTrace();         }       }   public void doDecrypt(String encryptText) throws NoSuchAlgorithmException{   RSAEncrypt encrypt = new RSAEncrypt();          KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");         keyPairGen.initialize(1024);          KeyPair keyPair = keyPairGen.generateKeyPair();          RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();          RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();                   // byte[] e = ' &r? ????gf??¦?_???(?)Z!-Dl?tA/??rl???`l???????iR?"|$?;D?I???|?F?JH???h???S?)u-?H??"`?M?2?#¢]?¬?6r?(??Y??:? b ';       //encrypt.encrypt(publicKey,encryptText.getBytes());                  byte[] de = encrypt.decrypt(privateKey, encryptText.getBytes());                   // System.out.println("加密:"+encrypt.bytesToString(e));             System.out.println("11111111111111");       System.out.println("解密:"+encrypt.bytesToString(de));   }    /** */      /**       * Change byte array to String.       *      * @return byte[]       */      protected String bytesToString(byte[] encrytpByte) {         String result = "";         for (Byte bytes : encrytpByte) {               result += (char) bytes.intValue();         }         return result;       }         /** */      /**       * Encrypt String.       *      * @return byte[]       */      protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {         if (publicKey != null) {               try {                   Cipher cipher = Cipher.getInstance("RSA");                   cipher.init(Cipher.ENCRYPT_MODE, publicKey);                   return cipher.doFinal(obj);               } catch (Exception e) {                   e.printStackTrace();               }         }         return null;       }         /** */      /**       * Basic decrypt method       *      * @return byte[]       */      protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {         if (privateKey != null) {               try {                   Cipher cipher = Cipher.getInstance("RSA");                   cipher.init(Cipher.DECRYPT_MODE, privateKey);                   return cipher.doFinal(obj);               } catch (Exception e) {                   e.printStackTrace();               }         }         return null;       }   }

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是一种数据加密算法,该算法经过加密专家多年来的发展和改进已日益完善,现在已成为公认的最安全的散列算法之一,并被广泛使用。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。散列函数值可以说时对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。
/**   * 加密解密   *    * @author shy.qiu   * @sincehttp://blog.csdn.net/qiushyfm   */public class Crypt {          /**       * 进行SHA加密       *      * @param info       *            要加密的信息       * @return String 加密后的字符串       */      public String encryptToSHA(String info) {         byte[] digesta = null;         try {               // 得到一个SHA-1的消息摘要               MessageDigest alga = MessageDigest.getInstance("SHA-1");               // 添加要进行计算摘要的信息               alga.update(info.getBytes());               // 得到该摘要               digesta = alga.digest();         } catch (NoSuchAlgorithmException e) {               e.printStackTrace();         }         // 将摘要转为字符串         String rs = byte2hex(digesta);         return rs;       }       // //////////////////////////////////////////////////////////////////////////       /**       * 创建密匙       *      * @param algorithm       *            加密算法,可用 DES,DESede,Blowfish       * @return SecretKey 秘密(对称)密钥       */      public SecretKey createSecretKey(String algorithm) {         // 声明KeyGenerator对象         KeyGenerator keygen;         // 声明 密钥对象         SecretKey deskey = null;         try {               // 返回生成指定算法的秘密密钥的 KeyGenerator 对象               keygen = KeyGenerator.getInstance(algorithm);               // 生成一个密钥               deskey = keygen.generateKey();         } catch (NoSuchAlgorithmException e) {               e.printStackTrace();         }         // 返回密匙         return deskey;       }       /**       * 根据密匙进行DES加密       *      * @param key       *            密匙       * @param info       *            要加密的信息       * @return String 加密后的信息       */      public String encryptToDES(SecretKey key, String info) {         // 定义 加密算法,可用 DES,DESede,Blowfish         String Algorithm = "DES";         // 加密随机数生成器 (RNG),(可以不写)         SecureRandom sr = new SecureRandom();         // 定义要生成的密文         byte[] cipherByte = null;         try {               // 得到加密/解密器               Cipher c1 = Cipher.getInstance(Algorithm);               // 用指定的密钥和模式初始化Cipher对象               // 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)               c1.init(Cipher.ENCRYPT_MODE, key, sr);               // 对要加密的内容进行编码处理,               cipherByte = c1.doFinal(info.getBytes());         } catch (Exception e) {               e.printStackTrace();         }         // 返回密文的十六进制形式         return byte2hex(cipherByte);       }       /**       * 根据密匙进行DES解密       *      * @param key       *            密匙       * @param sInfo       *            要解密的密文       * @return String 返回解密后信息       */      public String decryptByDES(SecretKey key, String sInfo) {         // 定义 加密算法,         String Algorithm = "DES";         // 加密随机数生成器 (RNG)         SecureRandom sr = new SecureRandom();         byte[] cipherByte = null;         try {               // 得到加密/解密器               Cipher c1 = Cipher.getInstance(Algorithm);               // 用指定的密钥和模式初始化Cipher对象               c1.init(Cipher.DECRYPT_MODE, key, sr);               // 对要解密的内容进行编码处理               cipherByte = c1.doFinal(hex2byte(sInfo));         } catch (Exception e) {               e.printStackTrace();         }         // return byte2hex(cipherByte);         return new String(cipherByte);       }       // /////////////////////////////////////////////////////////////////////////////       /**       * 创建密匙组,并将公匙,私匙放入到指定文件中       *      * 默认放入mykeys.bat文件中       * @throws IOException      */      public void createPairKey() throws IOException {         try {               // 根据特定的算法一个密钥对生成器               KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");               // 加密随机数生成器 (RNG)               SecureRandom random = new SecureRandom();               // 重新设置此随机对象的种子               random.setSeed(1000);               // 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器               keygen.initialize(512, random);// keygen.initialize(512);               // 生成密钥组               KeyPair keys = keygen.generateKeyPair();               // 得到公匙               PublicKey pubkey = keys.getPublic();               // 得到私匙               PrivateKey prikey = keys.getPrivate();             //取得公司名称,写入公钥中            GetProperties gp = new GetProperties();            String company = gp.getCompany();            // 将公匙私匙写入到文件当中               doObjToFile("mykeys.bat", new Object[] { prikey, pubkey ,company});         } catch (NoSuchAlgorithmException e) {               e.printStackTrace();         }       }       /**       * 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中       *      * @param info       *            要签名的信息       * @param signfile       *            存入的文件       */      public void signToInfo(String info, String signfile) {         // 从文件当中读取私匙         PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);         // 从文件中读取公匙         PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);         String in = (String) getObjFromFile("mykeys.bat", 3);      System.out.println("****"+in);      try {               // Signature 对象可用来生成和验证数字签名               Signature signet = Signature.getInstance("DSA");               // 初始化签署签名的私钥               signet.initSign(myprikey);               // 更新要由字节签名或验证的数据               signet.update(info.getBytes());               // 签署或验证所有更新字节的签名,返回签名               byte[] signed = signet.sign();               // 将数字签名,公匙,信息放入文件中               doObjToFile("d:\\"+signfile, new Object[] { signed, mypubkey, info ,in});         } catch (Exception e) {               e.printStackTrace();         }       }       /**       * 读取数字签名文件 根据公匙,签名,信息验证信息的合法性       *      * @return true 验证成功 false 验证失败       */      public boolean validateSign(String signfile) {         // 读取公匙         PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);         System.out.println("mypubkey==="+mypubkey);      // 读取签名         byte[] signed = (byte[]) getObjFromFile(signfile, 1);         // 读取信息         String info = (String) getObjFromFile(signfile, 3);         System.out.println("info==="+info);      try {               // 初始一个Signature对象,并用公钥和签名进行验证               Signature signetcheck = Signature.getInstance("DSA");               // 初始化验证签名的公钥               signetcheck.initVerify(mypubkey);               // 使用指定的 byte 数组更新要签名或验证的数据               signetcheck.update(info.getBytes());               // 验证传入的签名               return signetcheck.verify(signed);         } catch (Exception e) {               e.printStackTrace();               return false;         }       }       /**       * 将二进制转化为16进制字符串       *      * @param b       *            二进制字节数组       * @return String       */      public String byte2hex(byte[] b) {         String hs = "";         String stmp = "";         for (int n = 0; n < b.length; n++) {               stmp = (java.lang.Integer.toHexString(b & 0XFF));               if (stmp.length() == 1) {                   hs = hs + "0" + stmp;               } else {                   hs = hs + stmp;               }         }         return hs.toUpperCase();       }       /**       * 十六进制字符串转化为2进制       *      * @param hex       * @return       */      public byte[] hex2byte(String hex) {         byte[] ret = new byte;         byte[] tmp = hex.getBytes();         for (int i = 0; i < 8; i++) {               ret = uniteBytes(tmp, tmp);         }         return ret;       }       /**       * 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF       *      * @param src0       *            byte       * @param src1       *            byte       * @return byte       */      public static byte uniteBytes(byte src0, byte src1) {         byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))                   .byteValue();         _b0 = (byte) (_b0 << 4);         byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))                   .byteValue();         byte ret = (byte) (_b0 ^ _b1);         return ret;       }       /**       * 将指定的对象写入指定的文件       *      * @param file       *            指定写入的文件       * @param objs       *            要写入的对象       */      public void doObjToFile(String file, Object[] objs) {         ObjectOutputStream oos = null;         try {               FileOutputStream fos = new FileOutputStream(file);               oos = new ObjectOutputStream(fos);               for (int i = 0; i < objs.length; i++) {                   oos.writeObject(objs);               }         } catch (Exception e) {               e.printStackTrace();         } finally {               try {                   oos.close();               } catch (IOException e) {                   e.printStackTrace();               }         }       }       /**       * 返回在文件中指定位置的对象       *      * @param file       *            指定的文件       * @param i       *            从1开始       * @return       */      public Object getObjFromFile(String file, int i) {         ObjectInputStream ois = null;         Object obj = null;         try {               FileInputStream fis = new FileInputStream(file);               ois = new ObjectInputStream(fis);               for (int j = 0; j < i; j++) {                   obj = ois.readObject();               }         } catch (Exception e) {               e.printStackTrace();         } finally {               try {                   ois.close();               } catch (IOException e) {                   e.printStackTrace();               }         }         return obj;       }       /**       * 测试       *      * @param args       * @throws IOException      */      public static void main(String[] args) throws IOException {         Crypt jiami = new Crypt();         // 执行MD5加密"Hello world!"         System.out.println("Hello经过MD5:" + jiami.encryptToMD5("tanovo"));         // 生成一个DES算法的密匙         SecretKey key = jiami.createSecretKey("DES");         // 用密匙加密信息"Hello world!"         String str1 = jiami.encryptToDES(key, "tanovo");         System.out.println("使用des加密信息tanovo为:" + str1);         // 使用这个密匙解密         String str2 = jiami.decryptByDES(key, str1);         System.out.println("解密后为:" + str2);         // 创建公匙和私匙         jiami.createPairKey();         // 对Hello world!使用私匙进行签名         jiami.signToInfo("Hello", "mysign.bat");         // 利用公匙对签名进行验证。         if (jiami.validateSign("mysign.bat")) {               System.out.println("Success!");         } else {               System.out.println("Fail!");         }       }   }
页: [1]
查看完整版本: 加密解密整理