记录:
public abstract class RSACoderSignature {
private static final String PRIVATE_KEY = "RSAPrivate_Key";
private static final String PUBLIC_KEY = "RSAPublic_key";
private static final int KEY_SIZE = 512;
private static final String KEY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
public static byte[] getprivateKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return key.getEncoded();
}
public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return key.getEncoded();
}
/**
* 生产公私钥 保存到Map里面
* @return
* @throws Exception
*/
public static Map<String, Object> initKey() throws Exception {
Map<String, Object> keyMap = new HashMap<String, Object>(2);
KeyPairGenerator keyPaiGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPaiGen.initialize(KEY_SIZE);
KeyPair pair = keyPaiGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 用私钥生产数字签名,
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
PKCS8EncodedKeySpec pkc = new PKCS8EncodedKeySpec(privateKey);
KeyFactory keyfactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey prikey = keyfactory.generatePrivate(pkc);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initSign(prikey);
sig.update(data);
return sig.sign();
}
/**
* 用公钥decryption,检验私钥encryption的正确性,
* @param data
* @param publicKey
* @param signs 私钥生产的encryption数字证书
* @return
* @throws Exception
*/
public static boolean verify(byte[] data, byte[] publicKey, byte[] signs) throws Exception {
X509EncodedKeySpec pkc= new X509EncodedKeySpec(publicKey);
KeyFactory keyfactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey pubkey = keyfactory.generatePublic(pkc);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(pubkey);
sig.update(data);
return sig.verify(signs);
}
}