赞
踩
/**
* RSA加密工具类
* 使用PKCS1_PADDING填充,密钥长度1024
* 加解密结果在这里测试通过:http://tool.chacuo.net/cryptrsaprikey
* 注意加密内容的编码要一致,统一UTF-8比较好
* @author daxi
*/
public class RSAUtil {
public static final String KEY_ALGORTHM="RSA";
public static final String SIGNATURE_ALGORITHM="MD5withRSA";
public static final String PUBLIC_KEY = "RSAPublicKey";//公钥
public static final String PRIVATE_KEY = "RSAPrivateKey";//私钥
/**
* 初始化密钥
* RSA加密解密的实现,需要有一对公私密钥,公私密钥的初始化如下
* 非对称加密一般都用于加密对称加密算法的密钥,而不是直接加密内容
* @return
* @throws Exception
*/
public static Map initKey()throws Exception{
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORTHM);
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map keyMap = new HashMap(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 取得公钥,并转化为String类型
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map keyMap)throws Exception{
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Coder.encryptBASE64(key.getEncoded());
}
/**
* 取得私钥,并转化为String类型
* @param keyMap
* @return
* @throws Exception
*/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。