`

MD5算法学习及其对用户密码加密的应用收藏和RSA加密及解密3DEX加密解密

阅读更多

 前段时间有个客户提交了一个需求,说我们的系统中,subscriber的密码是以明文方式存在系统中的,不安全(汗颜啊……)。因此我们要做点改进,把subscriber的密码加一下密。借着机会,我也学习学习一下MD5算法(再次汗颜……)。

    MD5(Message-Digest Algorithm 5)加密算法是一种不可逆的算法,也即,即使源程序和算法描述可见,也无法将一个MD5值恢复到加密前的值。
    Message-Digest指的是字节串的Hash变换。这种变换只与字节的值有关,与字符集和编码方式无关。它将任意长字节串变换成一个128bit的 整数。相同的字节串计算出的MD5值总是相同的;不同的字节串计算出的MD5值是肯定不相同的。因此,MD5加密算法在日常生活中有许多应用。例如在很多系统和软件中,登录时所用的用户密码是以MD5值的方式保存的。用户注册时,将其设置的密码计算为MD5值并保存在数据库中。用户登录时,系统根据登录者输入的用户名计算出MD5值,与数据库中保存的该用户密码的MD5值进行比较,如果相同,才允许用户登录。
    MD5的另一个应用就是防止文件被“篡改”。如果一个文件被修改过,那么修改之前对文件计算出的MD5值和修改之后的MD5值是肯定不相同的。在实际开发过程中,developer们有时也会遇到MD5的应用。比如在version1,developer deliver了一个包module.rpm。然后我进行了修改,然后打包又生成了一个module.rpm,但是我想确认一下我现在做的rpm包是否是我做了修改后生成的包(有的时候也的确会出现这类问题)。我就需要比较一下前一个版本和后一个版本的module.rpm的MD5值。
    为了完成工作,我添加了一个工具类HashMD5,提供方法来对输入参数进行加密。
import java.security.*;
/**
 * @author Sam
 * Hash the input password, using MD5 algorithm.
 */
public class HashMD5 {
  public final static char hexChar[] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
  public static String convertBytesToString(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (int i=0; i<bytes.length; i++) {
      result.append(convertByteToHex(bytes[i]));
    }
    return result.toString();
  }
  private static String convertByteToHex(byte b) {
    int n = b;
    int d1 = 0;
    int d2 = 0;
    if (n<0){ 
      n = 256 + n;               
    } 
    d1 = n/16;
    d2 = n%16;
    StringBuffer str = new StringBuffer();
    str.append(hexChar[d1]).append(hexChar[d2]);
    return str.toString();
  }
 
  public static String Encryption(String inputpassword) {
    String encryptedPassword = null;
    try {
      byte[] strTmp = inputpassword.getBytes();
      MessageDigest mdTmp = MessageDigest.getInstance("MD5");
      mdTmp.update(strTmp);
      byte[] md = mdTmp.digest();
      encryptedPassword = convertBytesToString (md);
      return new String(encryptedPassword);
    }
    catch (Exception e){
    return null;
    }
  }
}
 出处:http://blog.csdn.net/lazy_tiger/archive/2007/11/20/1895050.aspx
Rsa 加密和解密算法:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;

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();
		}
	}

	/** */
	/**
	 * 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;
	}
}
 三:3DES 加密解密:测试过了支持中文,
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * 使用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("fenglingcompany");// 生成密匙

		String strEnc = des.getEncString("fengye666666666");// 加密字符串,返回String的密文
		System.out.println(strEnc);

		String strDes = des.getDesString(strEnc);// 把String 类型的密文解密 
		System.out.println(strDes);
	}

}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics