欢迎来到天天文库
浏览记录
ID:12939916
大小:36.00 KB
页数:3页
时间:2018-07-19
《java中的使用rsa算法进行公钥加密私钥解密》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、一个比较简单的实现:一个三个类KeyGenerater生成公钥私钥对,Signaturer类使用私钥签名,SignProvider用公钥验证。公钥和私钥使用Base64加密Base64这个类也在博客里面publicclassKeyGenerater{privatebyte[]priKey;privatebyte[]pubKey;publicvoidgenerater(){try{java.security.KeyPairGeneratorkeygen=java.security.KeyPairGenerator.getInst
2、ance("RSA");SecureRandomsecrand=newSecureRandom();secrand.setSeed("syj".getBytes());//初始化随机产生器keygen.initialize(1024,secrand);KeyPairkeys=keygen.genKeyPair();PublicKeypubkey=keys.getPublic();PrivateKeyprikey=keys.getPrivate();pubKey=Base64.encodeToByte(pubkey.getEnc
3、oded());priKey=Base64.encodeToByte(prikey.getEncoded());System.out.println("pubKey="+newString(pubKey));System.out.println("priKey="+newString(priKey));}catch(java.lang.Exceptione){System.out.println("生成密钥对失败");e.printStackTrace();}}publicbyte[]getPriKey(){returnpri
4、Key;}publicbyte[]getPubKey(){returnpubKey;}}publicclassSignaturer{/****Description:数字签名**@parampriKeyText*@paramplainText*@return*@author孙钰佳*@since:2007-12-27上午10:51:48*/publicstaticbyte[]sign(byte[]priKeyText,StringplainText){try{PKCS8EncodedKeySpecpriPKCS8=newPKCS
5、8EncodedKeySpec(Base64.decode(priKeyText));KeyFactorykeyf=KeyFactory.getInstance("RSA");PrivateKeyprikey=keyf.generatePrivate(priPKCS8);//用私钥对信息生成数字签名java.security.Signaturesignet=java.security.Signature.getInstance("MD5withRSA");signet.initSign(prikey);signet.updat
6、e(plainText.getBytes());byte[]signed=Base64.encodeToByte(signet.sign());returnsigned;}catch(java.lang.Exceptione){System.out.println("签名失败");e.printStackTrace();}returnnull;}}publicclassSignProvider{privateSignProvider(){}/****Description:校验数字签名,此方法不会抛出任务异常,成功返回true
7、,失败返回false,要求全部参数不能为空**@parampubKeyText*公钥,base64编码*@paramplainText*明文*@paramsignTest*数字签名的密文,base64编码*@return校验成功返回true失败返回false*@author孙钰佳*@since:2007-12-27上午09:33:55*/publicstaticbooleanverify(byte[]pubKeyText,StringplainText,byte[]signText){try{//解密由base64编码的公钥,
8、并构造X509EncodedKeySpec对象java.security.spec.X509EncodedKeySpecbobPubKeySpec=newjava.security.spec.X509EncodedKeySpec(Base64.decode(pubKeyTex
此文档下载收益归作者所有