熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java中常用的加密算法MD5,SHA,RSA

2013-11-23 19:24:02  來源: Java核心技術 

   MD加密常用於加密用戶名密碼當用戶驗證時

  

  protected byte[] encrypt(byte[] obj) {   try {   MessageDigest md = MessageDigestgetInstance(MD);   mdupdate(obj);   return mddigest();   } catch (NoSuchAlgorithmException e) {   eprintStackTrace();   }   }

   SHA加密與MD相似的用法只是兩者的算法不同

  

  protected byte[] encrypt(byte[] obj) {   try {   MessageDigest sha = MessageDigestgetInstance(SHA);   shaupdate(obj);   return shadigest();   } catch (NoSuchAlgorithmException e) {   eprintStackTrace();   }   }

   RSA加密RAS加密允許解密常用於文本內容的加密

  

  import javasecurityKeyPair;   import javasecurityKeyPairGenerator;   import javasecurityinterfacesRSAPrivateKey;   import javasecurityinterfacesRSAPublicKey;   import javaxcryptoCipher;  /** *//**   * RSAEncrypt   *   * @author maqujun   * @see   */   public class RSAEncrypt {   /** *//**   * Main method for RSAEncrypt   * @param args   */   public static void main(String[] args) {   try {   RSAEncrypt encrypt = new RSAEncrypt();   String encryptText = encryptText;   KeyPairGenerator keyPairGen = KeyPairGeneratorgetInstance(RSA);   keyPairGeninitialize();   KeyPair keyPair = keyPairGengenerateKeyPair();   // Generate keys   RSAPrivateKey privateKey = (RSAPrivateKey) keyPairgetPrivate();   RSAPublicKey publicKey = (RSAPublicKey) keyPairgetPublic();   byte[] e = encryptencrypt(publicKey encryptTextgetBytes());   byte[] de = encryptdecrypt(privateKeye);   Systemoutprintln(encryptbytesToString(e));   Systemoutprintln(encryptbytesToString(de));   } catch (Exception e) {   eprintStackTrace();   }   }   /** *//**   * Change byte array to String   * @return byte[]   */   protected String bytesToString(byte[] encrytpByte) {   String result = ;   for (Byte bytes : encrytpByte) {   result += (char) bytesintValue();   }   return result;   }   /** *//**   * Encrypt String   * @return byte[]   */   protected byte[] encrypt(RSAPublicKey publicKey byte[] obj) {   if (publicKey != null) {   try {   Cipher cipher = CiphergetInstance(RSA);   cipherinit(CipherENCRYPT_MODE publicKey);   return cipherdoFinal(obj);   } catch (Exception e) {   eprintStackTrace();   }   }   return null;   }   /** *//**   * Basic decrypt method   * @return byte[]   */   protected byte[] decrypt(RSAPrivateKey privateKey byte[] obj) {   if (privateKey != null) {   try {   Cipher cipher = CiphergetInstance(RSA);   cipherinit(CipherDECRYPT_MODE privateKey);   return cipherdoFinal(obj);   } catch (Exception e) {   eprintStackTrace();   }   }   return null;   }   }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26800.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.