Java 实现常见的非对称加密算法
概述
非对称加密算法与对称加密算法的主要差别在于非对称加密算法用于加密和解密的密钥不相同,非对称加密算法密钥分为公钥和私钥,公钥加密只能用私钥解密,反之私钥加密只能用公钥解密。相比对称加密算法,非对称加密算法加/解密效率低,但安全性高,这两种算法一般结合使用。常见非对称加密算法有RSA、ECC、Elgamal等。
使用RSA实现加密解密
公钥加密,私钥解密。
packagecom.ss.utils; importjavax.crypto.Cipher; importjava.security.KeyFactory; importjava.security.KeyPair; importjava.security.KeyPairGenerator; importjava.security.NoSuchAlgorithmException; importjava.security.spec.PKCS8EncodedKeySpec; importjava.security.spec.X509EncodedKeySpec; importjava.util.Base64; importjava.util.HashMap; importjava.util.Map; publicclassRsaUtil{ publicstaticfinalStringKEY_TYPE_PRIVATE_KEY="privateKey"; publicstaticfinalStringKEY_TYPE_PUBLIC_KEY="publicKey"; /** *生成公钥和私钥 * *@return *@throwsNoSuchAlgorithmException */ publicstaticMapgenerateKey()throwsNoSuchAlgorithmException{ Map resultMap=newHashMap<>(); KeyPairGeneratorkeyPairGenerator=KeyPairGenerator.getInstance("RSA"); KeyPairkeyPair=keyPairGenerator.generateKeyPair(); Base64.Encoderencoder=Base64.getEncoder(); resultMap.put(KEY_TYPE_PRIVATE_KEY,encoder.encodeToString(keyPair.getPrivate().getEncoded())); resultMap.put(KEY_TYPE_PUBLIC_KEY,encoder.encodeToString(keyPair.getPublic().getEncoded())); returnresultMap; } /** *RSA加密 *@paramkey *@paramcontent *@paramkeyType *@return *@throwsException */ publicstaticStringrsaEncrypt(Stringkey,Stringcontent,StringkeyType)throwsException{ returnrsa(key,content.getBytes(),keyType,Cipher.ENCRYPT_MODE); } /** *RSA解密 *@paramkey *@paramcontent *@paramkeyType *@return *@throwsException */ publicstaticStringrsaDecrypt(Stringkey,Stringcontent,StringkeyType)throwsException{ returnrsa(key,Base64.getDecoder().decode(content),keyType,Cipher.DECRYPT_MODE); } privatestaticStringrsa(Stringkey,byte[]content,StringkeyType,intmode)throwsException{ Ciphercipher=Cipher.getInstance("RSA"); KeyFactorykeyFactory=KeyFactory.getInstance("RSA"); if(KEY_TYPE_PRIVATE_KEY.equals(keyType)){ cipher.init(mode,keyFactory.generatePrivate(newPKCS8EncodedKeySpec(Base64.getDecoder().decode(key)))); }else{ cipher.init(mode,keyFactory.generatePublic(newX509EncodedKeySpec(Base64.getDecoder().decode(key)))); } byte[]bytes=cipher.doFinal(content); returnmode==Cipher.DECRYPT_MODE?newString(bytes):Base64.getEncoder().encodeToString(bytes); } publicstaticvoidmain(String[]args)throwsException{ Stringcontent="大王叫我来巡山呐"; //生成密钥对 Map keyMap=generateKey(); System.out.println("私钥:"+keyMap.get(KEY_TYPE_PRIVATE_KEY)); System.out.println("公钥:"+keyMap.get(KEY_TYPE_PUBLIC_KEY)); //私钥加密,公钥解密 StringprivateKeyData=rsaEncrypt(keyMap.get(KEY_TYPE_PRIVATE_KEY),content,KEY_TYPE_PRIVATE_KEY); System.out.println("私钥加密:"+privateKeyData); System.out.println("公钥解密:"+rsaDecrypt(keyMap.get(KEY_TYPE_PUBLIC_KEY),privateKeyData,KEY_TYPE_PUBLIC_KEY)); //公钥加密,私钥解密 StringpublicKeyData=rsaEncrypt(keyMap.get(KEY_TYPE_PUBLIC_KEY),content,KEY_TYPE_PUBLIC_KEY); System.out.println("公钥加密:"+publicKeyData); System.out.println("私钥解密:"+rsaDecrypt(keyMap.get(KEY_TYPE_PRIVATE_KEY),publicKeyData,KEY_TYPE_PRIVATE_KEY)); } }
输出
私钥:MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQPZnj0+/uh5jG0/rqVsXKLve7wTw2LVEwdBhm+SPrLoHYb4+6idNeF4bWgTqNRs2hfewq5cyiwXujT+eqp0g1ebSLWSUWzBsktynQMggxb8IwtnFYzmZX7BSAUudrfTre74RtKS0krYY5PCXCGR/EGbbXMVv1m2S59BrkWEI8c/iORhRAJ5/pqRW/51cIimPx9iTYx/QZC4VsCRi8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g+u3Tw8t5LOF+C7Gg/uxUP8Hm5jEkN6JfBHaMWTKg0RQ2xf3CCuXcLIpYVCOUwADwd05E8guEfZBT8FIp8jghCz2j+lAIiTfGZvsK9qUdZEmwTAEjV6uP4avF6njriglGJ4KhcYXEO66tOJWe2nQ1hyYXEHS43h9F0dtlWDjF6Xr6wdmUALnhprHDwKPdT/1T8p7+M5Fz7fUC7TJulBHWCSZvhgl405PvN+iTv7VysBJKRPks1JnmMe6BxFyhxXZfNRHmUyQvTMSfWt/A5gOy8ao/SOwWv0QMSh5NbocSd/tpjn27kw== 私钥解密:大王叫我来巡山呐
使用RSA实现数字签名
私钥签名,公钥验证。
packagecom.ss.utils; importjava.security.*; importjava.security.spec.PKCS8EncodedKeySpec; importjava.security.spec.X509EncodedKeySpec; importjava.util.Base64; importjava.util.HashMap; importjava.util.Map; publicclassSignatureUtil{ publicstaticfinalStringKEY_TYPE_PRIVATE_KEY="privateKey"; publicstaticfinalStringKEY_TYPE_PUBLIC_KEY="publicKey"; /** *生成公钥和私钥 * *@return *@throwsNoSuchAlgorithmException */ publicstaticMapgenerateKey()throwsNoSuchAlgorithmException{ Map resultMap=newHashMap<>(); KeyPairGeneratorkeyPairGenerator=KeyPairGenerator.getInstance("RSA"); KeyPairkeyPair=keyPairGenerator.generateKeyPair(); Base64.Encoderencoder=Base64.getEncoder(); resultMap.put(KEY_TYPE_PRIVATE_KEY,encoder.encodeToString(keyPair.getPrivate().getEncoded())); resultMap.put(KEY_TYPE_PUBLIC_KEY,encoder.encodeToString(keyPair.getPublic().getEncoded())); returnresultMap; } /** *私钥签名 *@paramprivateKeyStr *@paramcontent *@return *@throwsException */ publicstaticStringgenerateSignature(StringprivateKeyStr,Stringcontent)throwsException{ KeyFactorykeyFactory=KeyFactory.getInstance("RSA"); Signaturesignature=Signature.getInstance("SHA1withRSA"); PrivateKeyprivateKey=keyFactory.generatePrivate(newPKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyStr))); signature.initSign(privateKey); signature.update(content.getBytes()); returnBase64.getEncoder().encodeToString(signature.sign()); } /** *公钥验证 *@parampublicKeyStr *@paramcontent *@paramsign *@return *@throwsException */ publicstaticbooleanverifySignature(StringpublicKeyStr,Stringcontent,Stringsign)throwsException{ KeyFactorykeyFactory=KeyFactory.getInstance("RSA"); Signaturesignature=Signature.getInstance("SHA1withRSA"); PublicKeypublicKey=keyFactory.generatePublic(newX509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr))); signature.initVerify(publicKey); signature.update(content.getBytes()); returnsignature.verify(Base64.getDecoder().decode(sign)); } publicstaticvoidmain(String[]args)throwsException{ Stringcontent="大王叫我来巡山呐"; //生成密钥对 Map keyMap=generateKey(); //私钥签名 Stringsign=generateSignature(keyMap.get(KEY_TYPE_PRIVATE_KEY),content); System.out.println("私钥签名:"+sign); //公钥验证 booleanverifyResult=verifySignature(keyMap.get(KEY_TYPE_PUBLIC_KEY),content,sign); System.out.println("公钥验证:"+verifyResult); //将内容做下修改,再进行公钥验证 booleanverifyResult2=verifySignature(keyMap.get(KEY_TYPE_PUBLIC_KEY),content+"啦啦啦啦",sign); System.out.println("公钥验证:"+verifyResult2); } }
输出
私钥签名:XDWeOUVZhXNPl58mcmRK8ht9TAhnREc+NlnSs2b6PCJuj29ABuoXsjZeJqSspGw8hm9ckHVSTrUt8pX4BFBFzrINDRBsx3TdLp2L8nMkhjFUfo0qcyZo8ReEGFCNr0ergkq2W1Me/5W40GrQz4cJcQ4KV/QWzD8YHWcnDvKg9Q0nXJSngyhJTzUB8o/pgo/tmkA9+bWW212UD9nzEXu5aoPEcYyoo3iFWRX5o9Jgg6ZF+exmWizwZHkg4eD1zC5IN3m4yRS6GRbnZInEuDsOMp9W7HouDLUirkFZiSkyW+DVto+L6CE5eNBrWC52zxiNkVBlkyYKOatSpcrQrtnyiQ== 公钥验证:true 公钥验证:false
以上就是Java实现常见的非对称加密算法的详细内容,更多关于Java非对称加密算法的资料请关注毛票票其它相关文章!