`

RSA非对称加密算法Java实现

    博客分类:
  • java
 
阅读更多
package rsa;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

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

@SuppressWarnings({ "restriction" })
public class RSAUtils {

	/** 私有构造方法 */
	private RSAUtils() {
		super();
	}
	
	private static final Cipher CIPHER;
	
	static {
		try {
			CIPHER = Cipher.getInstance("RSA");
		} catch (Throwable e) {
			throw new InternalError(e.getMessage());
		}
	}

	//~ -----------------------------------------------------------------------------
	
	/**
	 * 生成私钥和公钥
	 * 
	 * @return KeyPair
	 */
	public static KeyPair generateKeyPair() {
		return generateKeyPair(1024);
	}
	
	/**
	 * 生成私钥和公钥
	 * 
	 * @param keySize 密钥长度
	 * @return KeyPair
	 */
	public static KeyPair generateKeyPair(int keySize) {
		KeyPairGenerator keyPairGen = null;
		try {
			keyPairGen = KeyPairGenerator.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			throw new InternalError(e.getMessage());
		}
		keyPairGen.initialize(keySize);
		return keyPairGen.generateKeyPair();
	}
	
	/**
	 * 从KeyPair中获得公钥
	 * 
	 * @param keyPair KeyPair
	 * @return 公钥
	 */
	public static PublicKey getPublicKey(KeyPair keyPair) {
		if (keyPair == null) {
			return null;
		}
		return keyPair.getPublic();
	}
	
	/**
	 * 从KeyPair中获得私钥
	 * 
	 * @param keyPair KeyPair
	 * @return 私钥
	 */
	public static PrivateKey getPrivateKey(KeyPair keyPair) {
		if (keyPair == null) {
			return null;
		}
		return keyPair.getPrivate();
	}
	
	/**
	 * 讲公钥或私钥转换为String
	 * 
	 * @param key 公钥/私钥
	 * @return 字符串
	 */
	public static String getKeyString(Key key) {
		if (key == null) {
			return null;
		}
		byte[] keyBytes = key.getEncoded();
		String s = (new BASE64Encoder()).encode(keyBytes);
		return s;
	}
	
	/**
	 * 得到公钥
	 * 
	 * @param key
	 *            密钥字符串(经过base64编码)
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(String key)  {
		byte[] keyBytes = null;
		try {
			keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		} catch (IOException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}

		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = null;
		try {
			keyFactory = KeyFactory.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			throw new InternalError(e.getMessage());
		}
		PublicKey publicKey = null;
		try {
			publicKey = keyFactory.generatePublic(keySpec);
		} catch (InvalidKeySpecException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		return publicKey;
	}

	/**
	 * 得到私钥
	 * 
	 * @param key
	 *            密钥字符串(经过base64编码)
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String key) {
		byte[] keyBytes;
		try {
			keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		} catch (IOException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}

		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = null;
		try {
			keyFactory = KeyFactory.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			throw new InternalError(e.getMessage());
		}
		PrivateKey privateKey = null;
		try {
			privateKey = keyFactory.generatePrivate(keySpec);
		} catch (InvalidKeySpecException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		return privateKey;
	}
	
	/**
	 * 加密数据
	 * 
	 * @param data 原文
	 * @param key 公钥/私钥
	 * @return 密文
	 */
	public static byte[] encrypt(byte[] data, Key key) {
		try {
			CIPHER.init(Cipher.ENCRYPT_MODE, key);
		} catch (InvalidKeyException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		
		byte[] result = null;

		try {
			result = CIPHER.doFinal(data);
		} catch (IllegalBlockSizeException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		} catch (BadPaddingException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		return result;
	}
	
	/**
	 * 解密数据
	 * 
	 * @param data 密文
	 * @param key 公钥/私钥
	 * @return 原文
	 */
	public static byte[] decrypt(byte[] data, Key key) {
		try {
			CIPHER.init(Cipher.DECRYPT_MODE, key);
		} catch (InvalidKeyException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		
		byte[] result = null;
		
		try {
			result = CIPHER.doFinal(data);
		} catch (IllegalBlockSizeException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		} catch (BadPaddingException e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
		
		return result;
	}

}


用法
@Override
public String encryptPassword(String password) {
	if (password == null) {
		return null;
	}
	byte[] data = RSAUtils.encrypt(password.getBytes(), publicKey);
	return Base64.encodeBase64URLSafeString(data);
}

@Override
public String decryptPassword(String encryptedPassword) {
	if (encryptedPassword == null) {
		return null;
	}
	byte[] data = Base64.decodeBase64(encryptedPassword);
	return new String(RSAUtils.decrypt(data, privateKey));
}
分享到:
评论
1 楼 xiang_qi_li 2015-10-19  
怎么测试RSAUtils 类中的方法呢??直接用楼主上面的测试用法是不行啊!!

相关推荐

Global site tag (gtag.js) - Google Analytics