码迷,mamicode.com
首页 > 编程语言 > 详细

经典的数字签名算法-RSA

时间:2015-11-05 12:02:29      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

记录:

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

 

经典的数字签名算法-RSA

标签:

原文地址:http://www.cnblogs.com/hqfblogs/p/4938913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!