Java 实现常见的非对称加密算法
程序员文章站
2024-01-18 22:40:58
概述非对称加密算法与对称加密算法的主要差别在于非对称加密算法用于加密和解密的密钥不相同,非对称加密算法密钥分为公钥和私钥,公钥加密只能用私钥解密,反之私钥加密只能用公钥解密。相比对称加密算法,非对称加...
概述
非对称加密算法与对称加密算法的主要差别在于非对称加密算法用于加密和解密的密钥不相同,非对称加密算法密钥分为公钥和私钥,公钥加密只能用私钥解密,反之私钥加密只能用公钥解密。相比对称加密算法,非对称加密算法加/解密效率低,但安全性高,这两种算法一般结合使用。常见非对称加密算法有rsa、ecc、elgamal等。
使用rsa实现加密解密
公钥加密,私钥解密。
package com.ss.utils; import javax.crypto.cipher; import java.security.keyfactory; import java.security.keypair; import java.security.keypairgenerator; import java.security.nosuchalgorithmexception; import java.security.spec.pkcs8encodedkeyspec; import java.security.spec.x509encodedkeyspec; import java.util.base64; import java.util.hashmap; import java.util.map; public class rsautil { public static final string key_type_private_key = "privatekey"; public static final string key_type_public_key = "publickey"; /** * 生成公钥和私钥 * * @return * @throws nosuchalgorithmexception */ public static map<string, string> generatekey() throws nosuchalgorithmexception { map<string, string> resultmap = new hashmap<>(); keypairgenerator keypairgenerator = keypairgenerator.getinstance("rsa"); keypair keypair = keypairgenerator.generatekeypair(); base64.encoder encoder = base64.getencoder(); resultmap.put(key_type_private_key, encoder.encodetostring(keypair.getprivate().getencoded())); resultmap.put(key_type_public_key, encoder.encodetostring(keypair.getpublic().getencoded())); return resultmap; } /** * rsa加密 * @param key * @param content * @param keytype * @return * @throws exception */ public static string rsaencrypt(string key, string content, string keytype) throws exception { return rsa(key, content.getbytes(), keytype, cipher.encrypt_mode); } /** * rsa解密 * @param key * @param content * @param keytype * @return * @throws exception */ public static string rsadecrypt(string key, string content, string keytype) throws exception { return rsa(key, base64.getdecoder().decode(content), keytype, cipher.decrypt_mode); } private static string rsa(string key, byte[] content, string keytype, int mode) throws exception { cipher cipher = cipher.getinstance("rsa"); keyfactory keyfactory = keyfactory.getinstance("rsa"); if (key_type_private_key.equals(keytype)) { cipher.init(mode, keyfactory.generateprivate(new pkcs8encodedkeyspec(base64.getdecoder().decode(key)))); } else { cipher.init(mode, keyfactory.generatepublic(new x509encodedkeyspec(base64.getdecoder().decode(key)))); } byte[] bytes = cipher.dofinal(content); return mode == cipher.decrypt_mode ? new string(bytes) : base64.getencoder().encodetostring(bytes); } public static void main(string[] args) throws exception { string content = "大王叫我来巡山呐"; //生成密钥对 map<string, string> keymap = generatekey(); system.out.println("私钥:" + keymap.get(key_type_private_key)); system.out.println("公钥:" + keymap.get(key_type_public_key)); //私钥加密,公钥解密 string privatekeydata = 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)); //公钥加密,私钥解密 string publickeydata = 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/qzc4vscri8zrbaxcjhei4y/yzofhfitid4atis0z3yw3fvybkzjo3nexupcec5qalblwudky6e4ngqq51bjbcub78rgxfldavtfbu9vr7prdqrh7sd//kpiicjiljvmclg9egxrkhrlm2tagmbaaecggeaes75hm0mwoujba9b+pu3pedrhp91xryyvzsaf5byyg4jexuprf8+ck05rioexnevmfpm/3ek2al1uviszafea/ueqhgov+udtohe3ppettmnusc/c/o1jucjtpkv/grczcgnvad9cjz1hceetpuqklxn4j0v2icopkrh36zvu0szjku5ltt6iygbpk6qqlplnx93ez5wewlnuolgjf34jbdqpc/zzjhwc8/ave81cj3duqr55l9qiwzuomq2edwo1ucpaeqrssnawehbqjfsjmqtvg1yussvpigb5atpltu7eoolfmoqm3qoaxx7/fr9uu50whivyzrrykv4cdilcqkbgqduj6bh1wuqribu5zotljbs73rdyybs1uuhubizq3rqrno3+tmavu+7h3dppi0l21yvpjxupmuvkix+ka7hidqulxx0yzmsdqxmggot2qfejgduemfajw09jahnciwuxmn3f94xavv6n+hfhjy31rgpqhjfgn6qq16a3ni46cd6vwkbgqdfdorb9wm0h6qj8ayaquhaifjnxeozn0q2407f5kx8xkakwkai7ybgzbiyesxfte0advqlyrjbaby1iuw/ogos+ia5buzco+bqrp6rxzldyvclyxs3wfslpkko6wiscs+uof36mwwn34yyh/ktt8b/hunfud+pectkrklonkzzjqkbgqcsn9htbhygkmfujv2qa5s9ihzjazjs+mfsmld9tuqf8opjnjdzhnwew0b/rukpbn0q90xpkai3dlmrzfmlgwdagskppvm4//ywczgjirewycsejo85+8gx9cdgtcgcjmldjgzqo/zjvpi8i8deatkc/+gqohxa6duixkfmm9rbkwkbgfxiv0suh5+8hwkzn9e5zbnowqgzm6tai791ph1yw1ntlnocvgqtb41dits6ffdwtc7bryver89pq1gpjawvquespuktnxe2x8imsud4xu0mzlp5fpt2vgt2dmgrifqkl7w6t41jdija1az231fihm5nazgjaqyzqhsdkwbkys8faogbaocip4beln64pnvuztynznvt/5phb4ssz3s1wexytti7328zkasi3f7pjxch7gvixfei2t3acvwppajyvel3zg/jl2x6znsldw8kgnhaje221u3pzefeidviwwki/oxwtrqyoactelneb6lbm3tkdltwzoryqtixqgdtluleqle0 公钥:miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea0d2z49pv7oeyxtp66lbfyi73u8e8ni1rmhqyzvkj6y6b2g+puontxheg1oe6jubnox3skuxmosf7o0/nqqdinxm0i1klfswbjlcp0diimw/cmlzxwm5mv+wugflna3063u+ebsktjk2gotwlwhkfxbm21zfb9ztkufqa5fhcphp4jkyuqcef6akvv+dxcipj8fyk2mf0gqufbakyvgawwl3cyriugp2mzhyxyeya+ae4rngd8snxvcmysyanzxsbqxhnoamiwzclg5gohodyekudw4wqlae/eyfxs3wlbxwbvva+6uxaq4e7a//5kyoni4iyb5ncxvxof65b0zztkwidaqab 私钥加密:v9kg4o3ncei4a19t/v5431v9ek1piv3fzokfnrnbor/rbymwdx4rsgnheyuyn6/sbbd56r3ij5tupshxflchrzvh4ifd4ysbvnnems2frzlf3zvqmwrkdph6sj0deczi5n97vfh4b2tfylt8ix3t9lpwgej5mb7mxiypc56mza+zaqdduxwwsm6emm81ukn97wznasg8zxldbhrttvtwhszbdhrfqsgd2sb8zzuziuigtaig7u6slc5x9us3uvacxxvymcmxivutqtg3z4kt80ruh7xo0hl4cwk6p2tg0ncaiqn/5vkso2uxr/escb2rchwn3zbhtvyq83v/ehdtqw== 公钥解密:大王叫我来巡山呐 公钥加密:aartoyclfeiz1jt5nghptbxxlzeoovm+vwvg+u3tw8t5lof+c7gg/uxup8hm5jekn6jfbhamwtkg0rq2xf3ccuxclipyvcouwadwd05e8guefzbt8fip8jghcz2j+laiitfgzvsk9qudzemwtaejv6up4avf6njriglgj4khcyxeo66tojwe2nq1hyyxehs43h9f0dtlwdjf6xr6wdmualnhprhdwkpdt/1t8p7+m5fz7fuc7tjulbhwcszvhgl405pvn+itv7vysbjkrpks1jnmme6bxfyhxxzfnrhmuyqvtmsfwt/a5goy8ao/sowwv0qmsh5nbocsd/tpjn27kw== 私钥解密:大王叫我来巡山呐
使用rsa实现数字签名
私钥签名,公钥验证。
package com.ss.utils; import java.security.*; import java.security.spec.pkcs8encodedkeyspec; import java.security.spec.x509encodedkeyspec; import java.util.base64; import java.util.hashmap; import java.util.map; public class signatureutil { public static final string key_type_private_key = "privatekey"; public static final string key_type_public_key = "publickey"; /** * 生成公钥和私钥 * * @return * @throws nosuchalgorithmexception */ public static map<string, string> generatekey() throws nosuchalgorithmexception { map<string, string> resultmap = new hashmap<>(); keypairgenerator keypairgenerator = keypairgenerator.getinstance("rsa"); keypair keypair = keypairgenerator.generatekeypair(); base64.encoder encoder = base64.getencoder(); resultmap.put(key_type_private_key, encoder.encodetostring(keypair.getprivate().getencoded())); resultmap.put(key_type_public_key, encoder.encodetostring(keypair.getpublic().getencoded())); return resultmap; } /** * 私钥签名 * @param privatekeystr * @param content * @return * @throws exception */ public static string generatesignature(string privatekeystr, string content) throws exception { keyfactory keyfactory = keyfactory.getinstance("rsa"); signature signature = signature.getinstance("sha1withrsa"); privatekey privatekey = keyfactory.generateprivate(new pkcs8encodedkeyspec(base64.getdecoder().decode(privatekeystr))); signature.initsign(privatekey); signature.update(content.getbytes()); return base64.getencoder().encodetostring(signature.sign()); } /** * 公钥验证 * @param publickeystr * @param content * @param sign * @return * @throws exception */ public static boolean verifysignature(string publickeystr, string content, string sign) throws exception { keyfactory keyfactory = keyfactory.getinstance("rsa"); signature signature = signature.getinstance("sha1withrsa"); publickey publickey = keyfactory.generatepublic(new x509encodedkeyspec(base64.getdecoder().decode(publickeystr))); signature.initverify(publickey); signature.update(content.getbytes()); return signature.verify(base64.getdecoder().decode(sign)); } public static void main(string[] args) throws exception { string content = "大王叫我来巡山呐"; //生成密钥对 map<string, string> keymap = generatekey(); //私钥签名 string sign = generatesignature(keymap.get(key_type_private_key), content); system.out.println("私钥签名:" + sign); //公钥验证 boolean verifyresult = verifysignature(keymap.get(key_type_public_key), content, sign); system.out.println("公钥验证:" + verifyresult); //将内容做下修改,再进行公钥验证 boolean verifyresult2 = 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 非对称加密算法的资料请关注其它相关文章!
上一篇: 刘作虎没吹牛:一加今年影像会是第一