Demo下载地址:Demo
- RSA加签、验签、加密、解密
需commons-codec-1.8.jar
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
/**
* Created by PengL on 2016/5/24. RSA 加密解密 加签验签 注意:秘钥长度:1024
*/
public class RSA
{
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 获取公钥的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
* 获取私钥的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
* <p>
* 生成密钥对(公钥和私钥)
* </p>
*
* @return
* @throws Exception
*/
public static Map<String, Object> genKeyPair() throws Exception
{
final KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
final KeyPair keyPair = keyPairGen.generateKeyPair();
final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
final Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 签名字符串
*
* @param text
* 需要签名的字符串
* @param privateKey
* 私钥(BASE64编码)
*
* @param charset
* 编码格式
* @return 签名结果(BASE64编码)
*/
public static String sign(final String text, final String privateKey, final String charset) throws Exception
{
final byte[] keyBytes = Base64.decodeBase64(privateKey);
final PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
final KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
final PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
final Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(RSA.getContentBytes(text, charset));
final byte[] result = signature.sign();
return Base64.encodeBase64String(result);
}
/**
* 签名字符串
*
* @param text
* 需要签名的字符串
* @param sign
* 客户签名结果
* @param publicKey