資源描述:
《用java實現(xiàn)rsa加密》由會員上傳分享,免費在線閱讀,更多相關內(nèi)容在行業(yè)資料-天天文庫。
1、用java實現(xiàn)RSA加密java實現(xiàn)RSA加密流程分析:1、甲方構(gòu)建密鑰對兒,將公鑰公布給乙方,將私鑰保留。2、甲方使用私鑰加密數(shù)據(jù),然后用私鑰對加密后的數(shù)據(jù)簽名,發(fā)送給乙方簽名以及加密后的數(shù)據(jù);乙方使用公鑰、簽名來驗證待解密數(shù)據(jù)是否有效,如果有效使用公鑰對數(shù)據(jù)解密。3、乙方使用公鑰加密數(shù)據(jù),向甲方發(fā)送經(jīng)過加密后的數(shù)據(jù);甲方獲得加密數(shù)據(jù),通過私鑰解密。通過java代碼實現(xiàn)如下:importjava.security.Key;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.Key
2、PairGenerator;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.Signature;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importjava.ut
3、il.HashMap;importjava.util.Map;importjavax.crypto.Cipher;/***//***RSA安全編碼組件**@version1.0*@since1.0*/publicabstractclassRSACoderextendsCoder{publicstaticfinalStringKEY_ALGORITHM="RSA";publicstaticfinalStringSIGNATURE_ALGORITHM="MD5withRSA";privatestaticfinalStringPUBLIC_KEY="RSAPublicKey";private
4、staticfinalStringPRIVATE_KEY="RSAPrivateKey";/***//***用私鑰對信息生成數(shù)字簽名**@paramdata*加密數(shù)據(jù)*@paramprivateKey*私鑰**@return*@throwsException*/publicstaticStringsign(byte[]data,StringprivateKey)throwsException{//解密由base64編碼的私鑰byte[]keyBytes=decryptBASE64(privateKey);//構(gòu)造PKCS8EncodedKeySpec對象PKCS8EncodedKeyS
5、pecpkcs8KeySpec=newPKCS8EncodedKeySpec(keyBytes);//KEY_ALGORITHM指定的加密算法KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);//取私鑰匙對象PrivateKeypriKey=keyFactory.generatePrivate(pkcs8KeySpec);//用私鑰對信息生成數(shù)字簽名Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(priKe
6、y);signature.update(data);returnencryptBASE64(signature.sign());}/***//***校驗數(shù)字簽名**@paramdata*加密數(shù)據(jù)*@parampublicKey*公鑰*@paramsign*數(shù)字簽名**@return校驗成功返回true失敗返回false*@throwsException**/publicstaticbooleanverify(byte[]data,StringpublicKey,Stringsign)throwsE//解密由base64編碼的公鑰byte[]keyBytes=decryptBASE64(
7、publicKey);//構(gòu)造X509EncodedKeySpec對象X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);//KEY_ALGORITHM指定的加密算法KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);//取公鑰匙對象PublicKeypubKey=keyFactory.generatePublic(