Android網路傳輸中必用的兩個密碼編譯演算法:MD5 和 RSA (附java完成測試代碼)

來源:互聯網
上載者:User

MD5和RSA是網路傳輸中最常用的兩個演算法,瞭解這兩個演算法原理後就能大致知道加密是怎麼一回事了。但這兩種演算法使用環境有差異,剛好互補。

一、MD5演算法

首先MD5是無法復原的,只能加密而不能解密。比如明文是yanzi1225627,得到MD5加密後的字串是:14F2AE15259E2C276A095E7394DA0CA9 但不能由後面一大串反向推算出yanzi1225627.因此可以用來儲存使用者輸入的密碼在伺服器上。現在下載檔案校正檔案是否中途被篡改也是用的它,原理參見:http://blog.csdn.net/forgotaboutgirl/article/details/7258109 無論在Android上還是pc上用java實現MD5都比較容易,因為java已經把它做到了java.security.MessageDigest裡。下面是一個MD5Util.java類:

package org.md5.util;import java.security.MessageDigest;public class MD5Util {public final static String getMD5String(String s) {char hexDigits[] = { '0', '1', '2', '3', '4','5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };try {byte[] btInput = s.getBytes();//獲得MD5摘要演算法的 MessageDigest 對象MessageDigest mdInst = MessageDigest.getInstance("MD5");//使用指定的位元組更新摘要mdInst.update(btInput);//獲得密文byte[] md = mdInst.digest();//把密文轉換成十六進位的字串形式int j = md.length;char str[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];str[k++] = hexDigits[byte0 >>> 4 & 0xf];str[k++] = hexDigits[byte0 & 0xf];}return new String(str);}catch (Exception e) {e.printStackTrace();return null;}}}

通過下面兩行代碼調用:

/************************************MD5加密測試*****************************/
String srcString = "yanzi1225627";
System.out.println("MD5加密後 = " + MD5Util.getMD5String(srcString));

二、RSA加密

RSA是可逆的,一個字串可以經rsa加密後,經加密後的字串傳到對端如伺服器上,再進行解密即可。前提是伺服器知道解密的私密金鑰,當然這個私密金鑰最好不要再網路傳輸。RSA演算法描述中需要以下幾個變數:

1、p和q 是不相等的,足夠大的兩個質數。 p和q是保密的

2、n = p*q n是公開的

3、f(n) = (p-1)*(q-1)

4、e 是和f(n)互質的質數

5、計算參數d

6、經過上面5步計算得到公開金鑰KU=(e,n) 私密金鑰KR=(d,n)

下面兩篇文章對此有清晰的描述:

http://wenku.baidu.com/view/e53fbe36a32d7375a417801b.html

http://bank.hexun.com/2009-06-24/118958531.html

下面是java實現RSAUtil.java類:

package org.rsa.util;import javax.crypto.Cipher;import java.security.*;import java.security.spec.RSAPublicKeySpec;import java.security.spec.RSAPrivateKeySpec;import java.security.spec.InvalidKeySpecException;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.io.*;import java.math.BigInteger;/** * RSA 工具類。提供加密,解密,產生金鑰組等方法。 * 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。 * RSA加密原理概述   * RSA的安全性依賴於大數的分解,公開金鑰和私密金鑰都是兩個大素數(大於100的十進位位)的函數。   * 據猜測,從一個密鑰和密文推斷出明文的難度等同於分解兩個大素數的積   * ===================================================================   * (該演算法的安全性未得到理論的證明)   * ===================================================================   * 密鑰的產生:   * 1.選擇兩個大素數 p,q ,計算 n=p*q;   * 2.隨機播放加密金鑰 e ,要求 e 和 (p-1)*(q-1)互質   * 3.利用 Euclid 演算法計算解密密鑰 d , 使其滿足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互質)   * 4:至此得出公開金鑰為 (n,e) 私密金鑰為 (n,d)   * ===================================================================   * 加解密方法:   * 1.首先將要加密的資訊 m(二進位表示) 分成等長的資料區塊 m1,m2,...,mi 塊長 s(儘可能大) ,其中 2^s *@author 董利偉
*版本:
*描述:
*建立時間:2008-9-23 下午09:58:16
*檔案描述:
*修改者:
*修改日期:
*修改描述:
*/public class RSAUtil {//金鑰組private KeyPair keyPair = null;/** * 初始化金鑰組 */public RSAUtil(){try {this.keyPair = this.generateKeyPair();} catch (Exception e) {e.printStackTrace();}}/*** 產生金鑰組* @return KeyPair* @throws Exception*/private KeyPair generateKeyPair() throws Exception {try {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());//這個值關係到塊加密的大小,可以更改,但是不要太大,否則效率會低final int KEY_SIZE = 1024;keyPairGen.initialize(KEY_SIZE, new SecureRandom());KeyPair keyPair = keyPairGen.genKeyPair();return keyPair;} catch (Exception e) {throw new Exception(e.getMessage());}}/*** 產生公開金鑰* @param modulus* @param publicExponent* @return RSAPublicKey* @throws Exception*/private RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {KeyFactory keyFac = null;try {keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new Exception(ex.getMessage());}RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));try {return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);} catch (InvalidKeySpecException ex) {throw new Exception(ex.getMessage());}}/*** 產生私密金鑰* @param modulus* @param privateExponent* @return RSAPrivateKey* @throws Exception*/private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {KeyFactory keyFac = null;try {keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new Exception(ex.getMessage());}RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));try {return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);} catch (InvalidKeySpecException ex) {throw new Exception(ex.getMessage());}}/*** 加密* @param key 加密的密鑰* @param data 待加密的明文資料* @return 加密後的資料* @throws Exception*/public byte[] encrypt(Key key, byte[] data) throws Exception {try {Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());cipher.init(Cipher.ENCRYPT_MODE, key);//獲得加密塊大小,如:加密前資料為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;//因此共有2個加密塊,第一個127 byte第二個為1個byteint blockSize = cipher.getBlockSize();int outputSize = cipher.getOutputSize(data.length);//獲得加密塊加密後塊大小int leavedSize = data.length % blockSize;int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;byte[] raw = new byte[outputSize * blocksSize];int i = 0;while (data.length - i * blockSize > 0) {if (data.length - i * blockSize > blockSize)cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);elsecipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);//這裡面doUpdate方法不可用,查看原始碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中//,而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。i++;}return raw;} catch (Exception e) {throw new Exception(e.getMessage());}}/*** 解密* @param key 解密的密鑰* @param raw 已經加密的資料* @return 解密後的明文* @throws Exception*/public byte[] decrypt(Key key, byte[] raw) throws Exception {try {Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());cipher.init(cipher.DECRYPT_MODE, key);int blockSize = cipher.getBlockSize();ByteArrayOutputStream bout = new ByteArrayOutputStream(64);int j = 0;while (raw.length - j * blockSize > 0) {bout.write(cipher.doFinal(raw, j * blockSize, blockSize));j++;}return bout.toByteArray();} catch (Exception e) {throw new Exception(e.getMessage());}}/** * 返回公開金鑰 * @return * @throws Exception */public RSAPublicKey getRSAPublicKey() throws Exception{//擷取公開金鑰RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();//擷取公開金鑰係數(位元組數組形式)byte[] pubModBytes = pubKey.getModulus().toByteArray();//返回公開金鑰公用指數(位元組數組形式)byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();//產生公開金鑰RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);return recoveryPubKey;}/** * 擷取私密金鑰 * @return * @throws Exception */public RSAPrivateKey getRSAPrivateKey() throws Exception{//擷取私密金鑰RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();//返回私密金鑰係數(位元組數組形式)byte[] priModBytes = priKey.getModulus().toByteArray();//返回私密金鑰專用指數(位元組數組形式)byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();//產生私密金鑰RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);return recoveryPriKey;}}
測試代碼:

/****************************RSA加密解密測試********************************/
try {
RSAUtil rsa = new RSAUtil();
String str = "yanzi1225627";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
byte[] enRsaBytes = rsa.encrypt(pubKey,str.getBytes());
String enRsaStr = new String(enRsaBytes, "UTF-8");
System.out.println("加密後==" + enRsaStr);
System.out.println("解密後==" + new String(rsa.decrypt(priKey, rsa.encrypt(pubKey,str.getBytes()))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

下面是執行結果:

加密後==s?ko?1@lo????BJ?iE???1Ux?Kx&??=??n
O??l?>?????2r?y??8v-\A??`????r?t3?-3y?hjL?M??Se?Z???????~?"??e??XZ?苜?
解密後==yanzi1225627

上面代碼需要用到一個包rsa.jar,下載連結及上面的測試代碼我已打包,下載連結見下:

http://download.csdn.net/detail/yanzi1225627/7382263




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.