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类:
- "font-family:Comic Sans MS;font-size:18px;">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();
-
- 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类:
- "font-family:Comic Sans MS;font-size:18px;">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;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class RSAUtil {
-
-
- private KeyPair keyPair = null;
-
-
-
-
- public RSAUtil(){
- try {
- this.keyPair = this.generateKeyPair();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- 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());
- }
-
- }
-
-
-
-
-
-
-
-
- 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());
- }
-
- }
-
-
-
-
-
-
-
-
- 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());
- }
- }
-
-
-
-
-
-
-
-
- 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);
-
-
- int 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);
- else
- cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
-
-
- i++;
- }
- return raw;
- } catch (Exception e) {
- throw new Exception(e.getMessage());
- }
- }
-
-
-
-
-
-
-
-
- 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());
- }
- }
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
- 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