分类: android平台
2023-02-09 09:43:27
加密解密密钥是相同的。这些算法也叫秘密密钥算法或单密钥算法,它要求发送者和接收者在安全通信之前,商定一个密钥。对称算法的安全性依赖于密钥,泄漏密钥就意味着任何人都能对消息进行加密解密。只要通信需要保密,密钥就必须保密。
对称算法可分为两类。一次只对明文中的单个位(有时对字节)运算的算法称为序列算法或序列密码。另一类算法是对明文的一组位进行运算,这些位组称为分组,相应的算法称为分组算法或分组密码。现代计算机密码算法的典型分组长度为64位――这个长度大到足以防止分析破译,但又小到足以方便作用。
非对称算法也叫公开密钥加密,它是用两个数学相关的密钥对信息进行编码。在此系统中,其中一个密钥叫公开密钥,可随意发给期望与密钥持有者进行安全通信的人。公开密钥用于对信息加密。第二个密钥是私有密钥,属于密钥持有者,此人要仔细保存私有密钥。密钥持有者用私有密钥对收到的信息进行解密。
一般来说,都是公钥加密,私钥解密。如果系统双方需要相互通讯,可以生成两对密钥对。各自保存好自己的私钥和对方的公钥,用公钥加密,私钥进行解密
一般来说,涉及到秘钥之类的算法,都是可逆的。意思就是通过算法和秘钥加密之后,可以再次通过解密算法还原。常见的有des、3des、aes128、aes192、aes256 。其中aes后面的数字代表的是密钥长度。对称加密算法的安全性相对较低,比较适用的场景就是内网环境中的加解密。
常见的不可逆加密算法有md5,hmac,sha1、sha-224、sha-256、sha-384,和sha-512,其中sha-224、sha-256、sha-384,和sha-512我们可以统称为sha2加密算法,sha加密算法的安全性要比md5更高,而sha2加密算法比sha1的要高。其中sha后面的数字表示的是加密后的字符串长度,sha1默认会产生一个160位的信息摘要。
不可逆加密算法{banned}最佳大的特点就是不需要密钥
加密盐也是比较常听到的一个概念,盐就是一个随机字符串用来和我们的加密串拼接后进行加密。加盐主要是为了保证加密字符串的安全性。假如有一个加盐后的加密串,黑客通过一定手段得到这个加密串,他解密后拿到的明文,并不是我们加密前的字符串,而是加密前的字符串和盐组合的字符串,这样相对来说又增加了字符串的安全性
或者也可以用在签名,例如签名是对明文或者密文加盐后的签名,有人想串改数据,如果不知道这个盐和规则,那么接收方验签就会不通过,从而保证通讯的安全。
对称算法,数据加密标准,速度较快,适用于加密大量数据的场合。
是des的升级版,属于对称算法。可逆
代码:aesutil
package aes; import java.io.unsupportedencodingexception; import java.nio.charset.standardcharsets; import java.security.invalidkeyexception; import java.security.nosuchalgorithmexception; import java.security.securerandom; import java.util.base64; import javax.crypto.badpaddingexception; import javax.crypto.cipher; import javax.crypto.illegalblocksizeexception; import javax.crypto.keygenerator; import javax.crypto.nosuchpaddingexception; import javax.crypto.secretkey; import javax.crypto.spec.secretkeyspec; public class aesutil { /** * aes加密字符串 * * @param content * 需要被加密的字符串 * @param password * 加密需要的密码 * @return 密文 */ public static byte[] encrypt(string content, string password) { try { keygenerator kgen = keygenerator.getinstance("aes");// 创建aes的key生产者 kgen.init(128, new securerandom(password.getbytes()));// 利用用户密码作为随机数初始化出 //加密没关系,securerandom是生成安全随机数序列,password.getbytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行 secretkey secretkey = kgen.generatekey();// 根据用户密码,生成一个密钥 byte[] encodeformat = secretkey.getencoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回 secretkeyspec key = new secretkeyspec(encodeformat, "aes");// 转换为aes专用密钥 cipher cipher = cipher.getinstance("aes");// 创建密码器 byte[] bytecontent = content.getbytes("utf-8"); cipher.init(cipher.encrypt_mode, key);// 初始化为加密模式的密码器 byte[] result = cipher.dofinal(bytecontent);// 加密 return result; } catch (nosuchpaddingexception e) { e.printstacktrace(); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (unsupportedencodingexception e) { e.printstacktrace(); } catch (invalidkeyexception e) { e.printstacktrace(); } catch (illegalblocksizeexception e) { e.printstacktrace(); } catch (badpaddingexception e) { e.printstacktrace(); } return null; } /** * 解密aes加密过的字符串 * * @param content * aes加密过过的内容 * @param password * 加密时的密码 * @return 明文 */ public static byte[] decrypt(byte[] content, string password) { try { keygenerator kgen = keygenerator.getinstance("aes");// 创建aes的key生产者 kgen.init(128, new securerandom(password.getbytes())); secretkey secretkey = kgen.generatekey();// 根据用户密码,生成一个密钥 byte[] encodeformat = secretkey.getencoded();// 返回基本编码格式的密钥 secretkeyspec key = new secretkeyspec(encodeformat, "aes");// 转换为aes专用密钥 cipher cipher = cipher.getinstance("aes");// 创建密码器 cipher.init(cipher.decrypt_mode, key);// 初始化为解密模式的密码器 byte[] result = cipher.dofinal(content); return result; // 明文 } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (nosuchpaddingexception e) { e.printstacktrace(); } catch (invalidkeyexception e) { e.printstacktrace(); } catch (illegalblocksizeexception e) { e.printstacktrace(); } catch (badpaddingexception e) { e.printstacktrace(); } return null; } public static void main(string[] args) throws exception { string a = base64.getencoder().encodetostring("435678(*&*&^*&^%&^$%^#%#!@#$%^&%�|8752$".getbytes(standardcharsets.utf_8)); string b = new string(base64.getdecoder().decode(a.getbytes(standardcharsets.utf_8))); system.out.println(a ":" b); string content = "{'aaa':'111','bbb':'222'}"; string secretkey = "43567890|8752$"; system.out.println("需要加密的内容:" content); byte[] encrypt = encrypt(content, secretkey); system.out.println("加密后的2进制密文:"); system.out.println(new string(encrypt)); string hexstr = base64.getencoder().encodetostring(encrypt); system.out.println("base64编码后密文:" hexstr); byte[] byte2 = base64.getdecoder().decode(hexstr); system.out.println("解码后转换为2进制后密文:"); system.out.println(new string(byte2)); byte[] decrypt = decrypt(byte2, secretkey); system.out.println("解密后的内容:" new string(decrypt,"utf-8")); } }
公钥加密算法,非对称,可逆
代码:rsautil
result = generatersakey(default_rsa_key_size);\n string publickey = result.get(\"publickey\");\n string privatekey = result.get(\"privatekey\");\n// string publickey = \"miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeauazymb25s/ueifwmm2h74736dqqe4bvrdgnfwltm4pzdunc84ntav41qegbztby47o57m/ydvf6vmxjh25ejlsbbhls7fd7xhtkorskzqlekh0xcs2xa/akdwllbewunzvwmuqy8x3j2vnrilxzvjvqyxkfy0itmo8fq1xso6b/s5/raekpttiepfb2ciu9vmrtlocsnjvotupdwcoc79lts0g1q5bv4dn+uca+8/gubhs7vbth3olzt6gxtrjjrpxht4lqwsczqwkqhpg/8jqgnfqs7+r0kcyemg/411iazi9wyrgtsqji8sq2q7halzrxvjn+as7jjpvyi67jgkwidaqab\";\n// string privatekey = \"miievqibadanbgkqhkig9w0baqefaascbkcwggsjageaaoibaqc5rpkyhbmz+54h/awzyfvjvfp1bathu9eoa19aw0zg/n240lzie1q/jwosbtm1vljs7nub9gnv/q8xckfbl6owweggwzsupvedoq6uyrmot6qftekzbfr9qr3cwvt7bq3o9yy5dlxfepzwesgtfnwo+pjgqvjsk0yjx+rxfi7oh9ln9fp4qlo0h6kuhzwht28yu0ugkyenwho491zyglv0u1lsdvdkfxh2f5rxr7z+bruflu9u2hegtm3qbdngmms/gfpiwpawjmrcrac8b/wlcccwqzv5hqpzj6yb/jxuhpkj1zhezoxcolyxdarsccvlfe8mf4czumk+/klrskyragmbaaecggeabjc+8dvj4j1n+2iu4g2tqt2pqsf+lcx/3tc7+b49jo8puuucvwy3znuhktkzrxzisxv2aralslnicgswyrreigmmjb00jgs/llm/sxkhwxmt7iezxbmjuvtnc7jy+3qcrti+9vh4w1kehaqb8opl8hvobiu3m2kglog20a7sym5gpicub3eq6p30u47y7i2wsbmnmmu79rpu3q7lsneob9kdvv6ea6vukl3chy1qxfh6ofzs1ynjfjxy5rxt8u5juhr5lyrnop8mevptbtrh34ssm0uyckkgj6josrdjqo/dj**xixj+bwgg5/xbnq3pfeyeaqkrtzy+fmhsufoaqkbgqdpqpxpl05mduxcnc7i6f8lzqjnjzu1h9zwkuqe94fs3i3siws62sjx1pz66p9eeiost0t4ye9ndx2x04yyfucenhydftq5m5m9e2q1kkdnebut6xy4wcribkozuq07mlysn0kdbuimp/erp2w3hl5nzu/elkdjt7ym0otv3upp5wkbgqdlbyc4hcvk+f1kd/xjq2ljwf+c8khhfrllripf7qtb24dcrauwxbagbbckxx2g+3waswyf09ndaliwab/juuuhjm0ygxyr0k5lhci0/ec7hd3twtl/hryef3umkzekbqypzneyme6t0lsqjl3mxfqlqumu4h677qa9/dnh7dyhhqkbgqcfam/bj6s7iba6jvfmozpi91bkvraawlgbxl7nt/nu0ncgzc0vd6wxgj3hqorgltu0krfv8pfp45qkphnwga8xd5gduiw68500zum8chdygeqejvvjvnuhqfnfexmirpfjnpqkcnrqxwk5cvmtci7+ys/fw0uwddivamcbn4auawkbgcogvaivnk6wefeeqqtsl6uozjaypbionek4src2fpinmdnlgmyvbmm51/lzealqa5p6fv2ipd4gae4nmznew+4qprswgudk3+ijw1sfk7qdwkzpeivpvddawyeshb8a22tpwwvae5er3m459avup8ubvw4rodxd4ka6gu1fh31paogaynpkjncrdosqh0nkh0ld44ch6hd+zcztoad2eqk0t2spnkbsis1s9w0adreoxuv1edo/hn3p/bctucaax7ijtscs2f0atc/nia6ljbnk7oubbzib9v21l72zvz5st4c/h7izbqcxfs81489a7tthp+e1hzs/xepfto0pakr1gj0=\";\n system.out.println(\"公钥为:\" + publickey);\n system.out.println(\"私钥为:\" + privatekey);\n string plaintext = \"{'a':'1111','b':'2222'}\";\n string ciphertext = null;\n try {\n system.out.println(\"开始加密明文:\"+plaintext);\n ciphertext = encrypt(plaintext,publickey);\n } catch (exception e) {\n system.out.println(\"加密失败\");\n throw new runtimeexception(e);\n }\n system.out.println(\"得到的密文为:\"+ciphertext);\n string deciphering = decrypt(ciphertext,privatekey);\n system.out.println(\"解密后:\"+deciphering);\n }\n /**\n * 生成rsa 公私钥,可选长度为1025,2048位.\n */\n public static mapgeneratersakey(int keysize) {\n map result = new hashmap<>(2);\n try {\n keypairgenerator keypairgen = keypairgenerator.getinstance(key_algorithm);\n // 初始化密钥对生成器,密钥大小为1024 2048位\n keypairgen.initialize(keysize, new securerandom());\n // 生成一个密钥对,保存在keypair中\n keypair keypair = keypairgen.generatekeypair();\n // 得到公钥字符串\n result.put(\"publickey\", new string(base64.getencoder().encode(keypair.getpublic().getencoded())));\n // 得到私钥字符串\n result.put(\"privatekey\", new string(base64.getencoder().encode(keypair.getprivate().getencoded())));\n } catch (generalsecurityexception e) {\n e.printstacktrace();\n }\n return result;\n }\n\n /**\n * rsa私钥解密\n * @param str 解密字符串\n * @param privatekey 私钥\n * @return 明文\n */\n public static string decrypt(string str, string privatekey) {\n //64位解码加密后的字符串\n byte[] inputbyte;\n string outstr = \"\";\n try {\n inputbyte = base64.getdecoder().decode(str.getbytes(\"utf-8\"));\n //base64编码的私钥\n byte[] decoded = base64.getdecoder().decode(privatekey);\n rsaprivatekey prikey = (rsaprivatekey) keyfactory.getinstance(\"rsa\").generateprivate(new pkcs8encodedkeyspec(decoded));\n //rsa解密\n cipher cipher = cipher.getinstance(\"rsa\");\n cipher.init(cipher.decrypt_mode, prikey);\n outstr = new string(cipher.dofinal(inputbyte));\n } catch (unsupportedencodingexception | nosuchpaddingexception | invalidkeyexception | illegalblocksizeexception | badpaddingexception | invalidkeyspecexception | nosuchalgorithmexception e) {\n e.printstacktrace();\n }\n return outstr;\n }\n\n /**\n * rsa公钥加密\n * @param str 需要加密的字符串\n * @param publickey 公钥\n * @return 密文\n * @throws exception 加密过程中的异常信息\n */\n public static string encrypt(string str, string publickey) throws exception {\n //base64编码的公钥\n byte[] decoded = base64.getdecoder().decode(publickey);\n rsapublickey pubkey = (rsapublickey) keyfactory.getinstance(\"rsa\").generatepublic(new x509encodedkeyspec(decoded));\n //rsa加密\n cipher cipher = cipher.getinstance(\"rsa\");\n cipher.init(cipher.encrypt_mode, pubkey);\n string outstr = base64.getencoder().encodetostring(cipher.dofinal(str.getbytes(\"utf-8\")));\n return outstr;\n }\n public static string sign(string data, string prikey) throws exception {\n byte[] decoded = base64.getdecoder().decode(prikey);\n keyfactory keyfactory = keyfactory.getinstance(\"rsa\");\n privatekey privatekey = keyfactory.generateprivate(new x509encodedkeyspec(decoded));\n signature signature = signature.getinstance(\"md5withrsa\");\n signature.initsign(privatekey);\n signature.update(data.getbytes());\n\n return new string(base64.getencoder().encode(signature.sign()));\n }\n public static boolean verify(string pubkey, string sign, string data) throws exception{\n //获取keyfactory,指定rsa算法\n keyfactory keyfactory = keyfactory.getinstance(\"rsa\");\n //将base64编码的公钥字符串进行解码\n byte[] encodebyte = base64.getdecoder().decode(pubkey);\n //将base64解码后的字节数组,构造成x509encodedkeyspec对象,生成公钥对象\n publickey publickey = keyfactory.generatepublic(new x509encodedkeyspec(encodebyte));\n signature signature = signature.getinstance(\"md5withrsa\");\n //加载公钥\n signature.initverify(publickey);\n //更新原数据\n signature.update(data.getbytes(\"utf-8\"));\n //公钥验签(true-验签通过;false-验签失败)\n return signature.verify(base64.getdecoder().decode(sign));\n }\n}\n\n","classes":null}" data-cke-widget-keep-attr="0" data-cke-widget-upcasted="1" data-widget="codesnippet">package rsasha256; import javax.crypto.badpaddingexception; import javax.crypto.cipher; import javax.crypto.illegalblocksizeexception; import javax.crypto.nosuchpaddingexception; import java.io.unsupportedencodingexception; import java.security.*; import java.security.interfaces.rsaprivatekey; import java.security.interfaces.rsapublickey; import java.security.spec.invalidkeyspecexception; 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 { private static final int default_rsa_key_size = 2048; private static final string key_algorithm = "rsa"; private static final string signature_algorithm = "md5withrsa"; public static void main(string [] args){ map result = generatersakey(default_rsa_key_size); string publickey = result.get("publickey"); string privatekey = result.get("privatekey"); // string publickey = "miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeauazymb25s/ueifwmm2h74736dqqe4bvrdgnfwltm4pzdunc84ntav41qegbztby47o57m/ydvf6vmxjh25ejlsbbhls7fd7xhtkorskzqlekh0xcs2xa/akdwllbewunzvwmuqy8x3j2vnrilxzvjvqyxkfy0itmo8fq1xso6b/s5/raekpttiepfb2ciu9vmrtlocsnjvotupdwcoc79lts0g1q5bv4dn uca 8/gubhs7vbth3olzt6gxtrjjrpxht4lqwsczqwkqhpg/8jqgnfqs7 r0kcyemg/411iazi9wyrgtsqji8sq2q7halzrxvjn as7jjpvyi67jgkwidaqab"; // string privatekey = "miievqibadanbgkqhkig9w0baqefaascbkcwggsjageaaoibaqc5rpkyhbmz 54h/awzyfvjvfp1bathu9eoa19aw0zg/n240lzie1q/jwosbtm1vljs7nub9gnv/q8xckfbl6owweggwzsupvedoq6uyrmot6qftekzbfr9qr3cwvt7bq3o9yy5dlxfepzwesgtfnwo pjgqvjsk0yjx rxfi7oh9ln9fp4qlo0h6kuhzwht28yu0ugkyenwho491zyglv0u1lsdvdkfxh2f5rxr7z bruflu9u2hegtm3qbdngmms/gfpiwpawjmrcrac8b/wlcccwqzv5hqpzj6yb/jxuhpkj1zhezoxcolyxdarsccvlfe8mf4czumk /klrskyragmbaaecggeabjc 8dvj4j1n 2iu4g2tqt2pqsf lcx/3tc7 b49jo8puuucvwy3znuhktkzrxzisxv2aralslnicgswyrreigmmjb00jgs/llm/sxkhwxmt7iezxbmjuvtnc7jy 3qcrti 9vh4w1kehaqb8opl8hvobiu3m2kglog20a7sym5gpicub3eq6p30u47y7i2wsbmnmmu79rpu3q7lsneob9kdvv6ea6vukl3chy1qxfh6ofzs1ynjfjxy5rxt8u5juhr5lyrnop8mevptbtrh34ssm0uyckkgj6josrdjqo/dj**xixj bwgg5/xbnq3pfeyeaqkrtzy fmhsufoaqkbgqdpqpxpl05mduxcnc7i6f8lzqjnjzu1h9zwkuqe94fs3i3siws62sjx1pz66p9eeiost0t4ye9ndx2x04yyfucenhydftq5m5m9e2q1kkdnebut6xy4wcribkozuq07mlysn0kdbuimp/erp2w3hl5nzu/elkdjt7ym0otv3upp5wkbgqdlbyc4hcvk f1kd/xjq2ljwf c8khhfrllripf7qtb24dcrauwxbagbbckxx2g 3waswyf09ndaliwab/juuuhjm0ygxyr0k5lhci0/ec7hd3twtl/hryef3umkzekbqypzneyme6t0lsqjl3mxfqlqumu4h677qa9/dnh7dyhhqkbgqcfam/bj6s7iba6jvfmozpi91bkvraawlgbxl7nt/nu0ncgzc0vd6wxgj3hqorgltu0krfv8pfp45qkphnwga8xd5gduiw68500zum8chdygeqejvvjvnuhqfnfexmirpfjnpqkcnrqxwk5cvmtci7 ys/fw0uwddivamcbn4auawkbgcogvaivnk6wefeeqqtsl6uozjaypbionek4src2fpinmdnlgmyvbmm51/lzealqa5p6fv2ipd4gae4nmznew 4qprswgudk3 ijw1sfk7qdwkzpeivpvddawyeshb8a22tpwwvae5er3m459avup8ubvw4rodxd4ka6gu1fh31paogaynpkjncrdosqh0nkh0ld44ch6hd zcztoad2eqk0t2spnkbsis1s9w0adreoxuv1edo/hn3p/bctucaax7ijtscs2f0atc/nia6ljbnk7oubbzib9v21l72zvz5st4c/h7izbqcxfs81489a7tthp e1hzs/xepfto0pakr1gj0="; system.out.println("公钥为:" publickey); system.out.println("私钥为:" privatekey); string plaintext = "{'a':'1111','b':'2222'}"; string ciphertext = null; try { system.out.println("开始加密明文:" plaintext); ciphertext = encrypt(plaintext,publickey); } catch (exception e) { system.out.println("加密失败"); throw new runtimeexception(e); } system.out.println("得到的密文为:" ciphertext); string deciphering = decrypt(ciphertext,privatekey); system.out.println("解密后:" deciphering); } /** * 生成rsa 公私钥,可选长度为1025,2048位. */ public static map generatersakey(int keysize) { map result = new hashmap<>(2); try { keypairgenerator keypairgen = keypairgenerator.getinstance(key_algorithm); // 初始化密钥对生成器,密钥大小为1024 2048位 keypairgen.initialize(keysize, new securerandom()); // 生成一个密钥对,保存在keypair中 keypair keypair = keypairgen.generatekeypair(); // 得到公钥字符串 result.put("publickey", new string(base64.getencoder().encode(keypair.getpublic().getencoded()))); // 得到私钥字符串 result.put("privatekey", new string(base64.getencoder().encode(keypair.getprivate().getencoded()))); } catch (generalsecurityexception e) { e.printstacktrace(); } return result; } /** * rsa私钥解密 * @param str 解密字符串 * @param privatekey 私钥 * @return 明文 */ public static string decrypt(string str, string privatekey) { //64位解码加密后的字符串 byte[] inputbyte; string outstr = ""; try { inputbyte = base64.getdecoder().decode(str.getbytes("utf-8")); //base64编码的私钥 byte[] decoded = base64.getdecoder().decode(privatekey); rsaprivatekey prikey = (rsaprivatekey) keyfactory.getinstance("rsa").generateprivate(new pkcs8encodedkeyspec(decoded)); //rsa解密 cipher cipher = cipher.getinstance("rsa"); cipher.init(cipher.decrypt_mode, prikey); outstr = new string(cipher.dofinal(inputbyte)); } catch (unsupportedencodingexception | nosuchpaddingexception | invalidkeyexception | illegalblocksizeexception | badpaddingexception | invalidkeyspecexception | nosuchalgorithmexception e) { e.printstacktrace(); } return outstr; } /** * rsa公钥加密 * @param str 需要加密的字符串 * @param publickey 公钥 * @return 密文 * @throws exception 加密过程中的异常信息 */ public static string encrypt(string str, string publickey) throws exception { //base64编码的公钥 byte[] decoded = base64.getdecoder().decode(publickey); rsapublickey pubkey = (rsapublickey) keyfactory.getinstance("rsa").generatepublic(new x509encodedkeyspec(decoded)); //rsa加密 cipher cipher = cipher.getinstance("rsa"); cipher.init(cipher.encrypt_mode, pubkey); string outstr = base64.getencoder().encodetostring(cipher.dofinal(str.getbytes("utf-8"))); return outstr; } public static string sign(string data, string prikey) throws exception { byte[] decoded = base64.getdecoder().decode(prikey); keyfactory keyfactory = keyfactory.getinstance("rsa"); privatekey privatekey = keyfactory.generateprivate(new x509encodedkeyspec(decoded)); signature signature = signature.getinstance("md5withrsa"); signature.initsign(privatekey); signature.update(data.getbytes()); return new string(base64.getencoder().encode(signature.sign())); } public static boolean verify(string pubkey, string sign, string data) throws exception{ //获取keyfactory,指定rsa算法 keyfactory keyfactory = keyfactory.getinstance("rsa"); //将base64编码的公钥字符串进行解码 byte[] encodebyte = base64.getdecoder().decode(pubkey); //将base64解码后的字节数组,构造成x509encodedkeyspec对象,生成公钥对象 publickey publickey = keyfactory.generatepublic(new x509encodedkeyspec(encodebyte)); signature signature = signature.getinstance("md5withrsa"); //加载公钥 signature.initverify(publickey); //更新原数据 signature.update(data.getbytes("utf-8")); //公钥验签(true-验签通过;false-验签失败) return signature.verify(base64.getdecoder().decode(sign)); } }
信息摘要(hash安全散列)算法,也叫哈希算法,哈希值也叫散列值,不可逆,不需要秘钥。
代码: md5util
package md5; import java.nio.charset.standardcharsets; import java.security.messagedigest; import java.security.nosuchalgorithmexception; public class md5util { public static void main(string[] args) { string sha256str = getsha256str("123456"); system.out.println(sha256str); } /** * sha256加密 * * @param str 要加密的字符串 * @return 加密后的字符串 */ public static string getsha256str(string str) { messagedigest messagedigest; string encodestr = ""; try { messagedigest = messagedigest.getinstance("md5"); messagedigest.update(str.getbytes(standardcharsets.utf_8)); encodestr = byte2hex(messagedigest.digest()); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } return encodestr; } /** * sha256加密 将byte转为16进制 * * @param bytes 字节码 * @return 加密后的字符串 */ private static string byte2hex(byte[] bytes) { stringbuilder stringbuilder = new stringbuilder(); string temp; for (byte abyte : bytes) { temp = integer.tohexstring(abyte & 0xff); if (temp.length() == 1) { //1得到一位的进行补0操作 stringbuilder.append("0"); } stringbuilder.append(temp); } return stringbuilder.tostring(); } }
sha256算法也是一种密码散列函数,对于任意长度的消息,sha256都会产生一个256bit长的散列值(哈希值),用于确保信息传输完整一致,称作消息摘要。这个摘要相当于是个长度为32个字节的数组,通常用一个长度为64的十六进制字符串来表示。
和md5算法对比
相同点:
1、都是密码散列函数,加密不可逆。
2、都可以实现对任意长度对象加密,都不能防止碰撞。
安全性方面:
1、sha256(称sha2)的安全性{banned}最佳高,但是耗时要其他两种多很多。
2、md5相对来说比较容易碰撞,安全性没这么高。
性能方面:
以个60m的件为测试样本,经过1000次的测试平均值,这两种算法的表现如下:
md5算法运1000次的平均时间为:226ms
sha256算法运1000次的平均时间为:473ms
总而言之,md5和sha256都是密码散列函数,加密不可逆。虽然都不能防止碰撞,但是相对而言,md5比较容易碰撞,安全性没有sha256高。
代码:sha256util
package rsasha256; import java.nio.charset.standardcharsets; import java.security.messagedigest; import java.security.nosuchalgorithmexception; public class sha256util { public static void main(string[] args) { string sha256str = getsha256str("123456"); system.out.println(sha256str); } /** * sha256加密 * * @param str 要加密的字符串 * @return 加密后的字符串 */ public static string getsha256str(string str) { messagedigest messagedigest; string encodestr = ""; try { messagedigest = messagedigest.getinstance("sha-256"); messagedigest.update(str.getbytes(standardcharsets.utf_8)); encodestr = byte2hex(messagedigest.digest()); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } return encodestr; } /** * sha256加密 将byte转为16进制 * * @param bytes 字节码 * @return 加密后的字符串 */ private static string byte2hex(byte[] bytes) { stringbuilder stringbuilder = new stringbuilder(); string temp; for (byte abyte : bytes) { temp = integer.tohexstring(abyte & 0xff); if (temp.length() == 1) { //1得到一位的进行补0操作 stringbuilder.append("0"); } stringbuilder.append(temp); } return stringbuilder.tostring(); } }
为保障国家密码应用安全,2011年gjmm管理局发布《关于做好公钥密码算法升级工作的通知》,
要求自2011年3月1日起在建和拟建公钥密码基础设施电子认证系统和密钥管理系统应使用国密算法。
《金融和重要领域密码应用与创新发展工作规划(2018-2022年) 》以及相关法规文件也要求我国金融
和重要领域密码应用采用sm2国产密码算法体系。
国密算法是指gjmm管理局认定的一系列国产密码算法,包括sm1-sm9以及zuc等。
其中sm1、sm4、sm5、sm6、sm7、sm8、zuc等属于对称密码,sm2、sm9等属于公钥密码,sm3属于单向散列函数。
目前我国主要使用公开的sm2、sm3、sm4作为商用密码。
sm1也叫商密1号算法,是一种国产的对称算法,分组长度和密钥长度都为 128 比特,该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。算法安全保密强度及相关软硬件实现性能与 aes 相当
sm2算法和rsa算法都是公钥密码算法,sm2算法是一种更先进安全的算法,在我们国家商用密码体系中被用来替换rsa算法。
随着密码技术和计算机技术的发展,目前常用的1024位rsa算法面临严重的安全威胁,我们国家密码管理部门经过研究,决定采用sm2椭圆曲线算法替换rsa算法。
代码:sm2util
package gmsm; import org.bouncycastle.asn1.gm.gmnamedcurves; import org.bouncycastle.asn1.x9.x9ecparameters; import org.bouncycastle.crypto.cryptoexception; import org.bouncycastle.crypto.invalidciphertextexception; import org.bouncycastle.crypto.engines.sm2engine; import org.bouncycastle.crypto.params.*; import org.bouncycastle.crypto.signers.sm2signer; import org.bouncycastle.jce.provider.bouncycastleprovider; import org.bouncycastle.math.ec.eccurve; import org.bouncycastle.math.ec.ecpoint; import org.bouncycastle.util.strings; import org.bouncycastle.util.encoders.base64; import org.bouncycastle.util.encoders.hex; import java.math.biginteger; import java.nio.charset.charset; import java.security.keypair; import java.security.keypairgenerator; import java.security.nosuchalgorithmexception; import java.security.securerandom; import java.security.spec.ecgenparameterspec; /** * sm2 工具类 * */ public class sm2util { //sm2推荐曲线名称 static string sm2_curve_name = "sm2p256v1"; public static final charset utf_8 = charset.forname("utf-8"); /** * 生成密钥 * * @return * @throws exception */ public static keypair genkeypair() throws exception { final ecgenparameterspec sm2spec = new ecgenparameterspec(sm2_curve_name); // 获取一个椭圆曲线类型的密钥对生成器 final keypairgenerator kpg = keypairgenerator.getinstance("ec", new bouncycastleprovider()); securerandom random = new securerandom(); // 使用sm2的算法区域初始化密钥生成器 kpg.initialize(sm2spec, random); // 获取密钥对 keypair keypair = kpg.generatekeypair(); return keypair; } /**sm2根据公钥加密 * param: message 待加密内容 , publickey 加密公钥(base64编码) * return: 加密信息的base64编码 * @throws invalidciphertextexception * */ public static string encryptbysm2(string message, string publickey) throws invalidciphertextexception { ecdomainparameters domin = getdomain(); //公钥对象 ecpublickeyparameters pubkeyparameters = getpubkey(publickey,domin); byte[] cipherbytes = new byte[0]; cipherbytes = encrypt(sm2engine.mode.c1c3c2, pubkeyparameters, message.getbytes(utf_8)); return base64.tobase64string(cipherbytes); } /** * sm2根据私钥解密 * param: ciphertext 待解密密文 privatekey-私钥(base64编码) * */ public static string decryptbysm2(string ciphertext, string privatekey) throws invalidciphertextexception { biginteger d = new biginteger(1,base64.decode(privatekey)); ecdomainparameters domin = getdomain(); //私钥对象 ecprivatekeyparameters ecprivatekeyparameters = new ecprivatekeyparameters(d, domin); byte[] decrypt = decrypt(sm2engine.mode.c1c3c2, ecprivatekeyparameters, base64.decode(ciphertext)); return new string(decrypt,utf_8); } /** * 根据公钥字符串创建公钥对象 * * */ public static ecpublickeyparameters getpubkey(string publickey, ecdomainparameters domain) { eccurve curve = domain.getcurve(); ecpoint point = curve.decodepoint(base64.decode(publickey)); ecpublickeyparameters publickey = new ecpublickeyparameters(point, domain); return publickey; } /** * @param mode 指定密文结构,旧标准的为c1c2c3,新的[《sm2密码算法使用规范》 gm/t 0009-2012]标准为c1c3c2 * @param pubkeyparameters 公钥 * @param srcdata 原文 * @return 根据mode不同,输出的密文c1c2c3排列顺序不同。c1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。c3为32字节。c2长度与原文一致。 * @throws invalidciphertextexception */ public static byte[] encrypt(sm2engine.mode mode, ecpublickeyparameters pubkeyparameters, byte[] srcdata) throws invalidciphertextexception { sm2engine engine = new sm2engine(mode); parameterswithrandom pwr = new parameterswithrandom(pubkeyparameters, new securerandom()); engine.init(true, pwr); return engine.processblock(srcdata, 0, srcdata.length); } /** * @param mode 指定密文结构,旧标准的为c1c2c3,新的[《sm2密码算法使用规范》 gm/t 0009-2012]标准为c1c3c2 * @param prikeyparameters 私钥 * @param sm2cipher 根据mode不同,需要输入的密文c1c2c3排列顺序不同。c1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。c3为32字节。c2长度与原文一致。 * @return 原文。sm2解密返回了数据则一定是原文,因为sm2自带校验,如果密文被篡改或者密钥对不上,都是会直接报异常的。 * @throws invalidciphertextexception */ public static byte[] decrypt(sm2engine.mode mode, ecprivatekeyparameters prikeyparameters, byte[] sm2cipher) throws invalidciphertextexception { sm2engine engine = new sm2engine(mode); engine.init(false, prikeyparameters); return engine.processblock(sm2cipher, 0, sm2cipher.length); } public static ecdomainparameters getdomain() { //获取一条sm2曲线参数 x9ecparameters x9ecparameters = gmnamedcurves.getbyname(sm2_curve_name); //构造domain参数 ecdomainparameters domain = new ecdomainparameters( x9ecparameters.getcurve(), x9ecparameters.getg(), x9ecparameters.getn(), x9ecparameters.geth() ); return domain; } /** * 私钥签名 * @param privatekey 私钥 * @param content 待签名内容 * @return */ public static string sign(string privatekey, string content) throws cryptoexception, cryptoexception { //待签名内容转为字节数组 byte[] message = content.getbytes(); biginteger domainparameters = new biginteger(1,base64.decode(privatekey)); ecdomainparameters domin = getdomain(); //私钥对象 ecprivatekeyparameters privatekeyparameters = new ecprivatekeyparameters(domainparameters, domin); //创建签名实例 sm2signer sm2signer = new sm2signer(); //初始化签名实例,带上id,国密的要求,id默认值:1234567812345678 try { sm2signer.init(true, new parameterswithid(new parameterswithrandom(privatekeyparameters, securerandom.getinstance("sha1prng")), strings.tobytearray("1234567812345678"))); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } sm2signer.update(message, 0, message.length); //生成签名,签名分为两部分r和s,分别对应索引0和1的数组 byte[] signbytes = sm2signer.generatesignature(); string sign = base64.tobase64string(signbytes); return sign; } /** * 验证签名 * @param publickey 公钥 * @param content 待签名内容 * @param sign 签名值 * @return */ public static boolean verify(string publickey, string content, string sign) { //待签名内容 byte[] message = content.getbytes(); byte[] signdata = base64.decode(sign); // 获取一条sm2曲线参数 x9ecparameters sm2ecparameters = gmnamedcurves.getbyname(sm2_curve_name); // 构造domain参数 ecdomainparameters domainparameters = new ecdomainparameters(sm2ecparameters.getcurve(), sm2ecparameters.getg(), sm2ecparameters.getn()); //提取公钥点 ecpoint pukpoint = sm2ecparameters.getcurve().decodepoint(java.util.base64.getdecoder().decode(publickey)); // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04 ecpublickeyparameters publickeyparameters = new ecpublickeyparameters(pukpoint, domainparameters); //创建签名实例 sm2signer sm2signer = new sm2signer(); parameterswithid parameterswithid = new parameterswithid(publickeyparameters, strings.tobytearray("1234567812345678")); sm2signer.init(false, parameterswithid); sm2signer.update(message, 0, message.length); //验证签名结果 boolean verify = sm2signer.verifysignature(signdata); return verify; } }
国产哈希算法,也叫消息摘要算法,可以用md5作为对比理解。该算法已公开。校验结果为256位。sm3是中华人民共和国政府采用的一种密码散列函数标准,由gjmm管理局于2010年12月17日发布。相关标准为“gm/t 0004-2012 《sm3密码杂凑算法》”。
在商用密码体系中,sm3主要用于数字签名及验证、消息认证码生成及验证、随机数生成等,其算法公开。据gjmm管理局表示,其安全性及效率与sha-256相当。
代码:sm3util
package gmsm; import org.bouncycastle.crypto.digests.sm3digest; import org.bouncycastle.util.encoders.hex; import java.util.arrays; public class sm3util { /** * 计算sm3摘要值 * * @param srcdata 原文 * @return 摘要值,对于sm3算法来说是32字节 */ public static byte[] hash(byte[] srcdata) { sm3digest digest = new sm3digest(); digest.update(srcdata, 0, srcdata.length); byte[] hash = new byte[digest.getdigestsize()]; digest.dofinal(hash, 0); return hash; } /** * 验证摘要 * * @param srcdata 原文 * @param sm3hash 摘要值 * @return 返回true标识验证成功,false标识验证失败 */ public static boolean verify(byte[] srcdata, byte[] sm3hash) { byte[] newhash = hash(srcdata); system.out.println(hex.tohexstring(newhash)); system.out.println(hex.tohexstring(sm3hash)); if (arrays.equals(newhash, sm3hash)) { return true; } else { return false; } } }
无线局域网标准的分组数据算法。对称加密,密钥长度和分组长度均为128位。对标aes
代码:sm4util
package gmsm; import org.bouncycastle.jce.provider.bouncycastleprovider; import javax.crypto.cipher; import javax.crypto.keygenerator; import javax.crypto.spec.ivparameterspec; import javax.crypto.spec.secretkeyspec; import java.security.*; public class sm4util { static { security.addprovider(new bouncycastleprovider()); } public static final string algorithm_name = "sm4"; // aes public static final string default_key = "random_seed"; // 128-32位16进制;256-64位16进制 public static final int default_key_size = 128; public static byte[] generatekey() throws nosuchalgorithmexception, nosuchproviderexception { return generatekey(default_key, default_key_size); } public static byte[] generatekey(string seed) throws nosuchalgorithmexception, nosuchproviderexception { return generatekey(seed, default_key_size); } public static byte[] generatekey(string seed, int keysize) throws nosuchalgorithmexception, nosuchproviderexception { keygenerator kg = keygenerator.getinstance(algorithm_name, bouncycastleprovider.provider_name); securerandom random = securerandom.getinstance("sha1prng"); if (null != seed && !"".equals(seed)) { random.setseed(seed.getbytes()); } kg.init(keysize, random); return kg.generatekey().getencoded(); } /** * @description 加密 */ public static byte[] encrypt(string algorithmname, byte[] key, byte[] iv, byte[] data) throws exception { return sm4core(algorithmname, cipher.encrypt_mode, key, iv, data); } /** * @description 解密 */ public static byte[] decrypt(string algorithmname, byte[] key, byte[] iv, byte[] data) throws exception { return sm4core(algorithmname, cipher.decrypt_mode, key, iv, data); } private static byte[] sm4core(string algorithmname, int type, byte[] key, byte[] iv, byte[] data) throws exception { cipher cipher = cipher.getinstance(algorithmname, bouncycastleprovider.provider_name); key sm4key = new secretkeyspec(key, algorithm_name); if (algorithmname.contains("/ecb/")) { cipher.init(type, sm4key); } else { if(iv == null ){ cipher.init(type, sm4key); }else{ ivparameterspec ivparameterspec = new ivparameterspec(iv); cipher.init(type, sm4key, ivparameterspec); } } return cipher.dofinal(data); } }
在支付系统交互中,有多种多样的加密方式组合,这里就简单介绍两钟常用的。
用可逆,非对称算法(rsa,sm2等)使用对方公钥对报文内的关键信息进行加密,得到的密文进行编码,然后再对密文编码后的串加盐后使用不可逆算法(sha256,md5,sm3等)进行签名,使用这些算法签名后得到的是一个16进制的串,签名放到另一个字段,一般是和加密后的信息并列的。
步骤:
1.使用对方的rsa公钥对明文进行加密,得到的密文进行base64编码,作为data
2.将data的值加上约定好的盐,使用sha256算法进行签名,得到的签名是16进制的串,放到sign
加密后的json:
{ "data": "auwpdinowtdseztfccr8b1opsevje1mqivoln56wdvw3gjkssjkpmgp4lpyiqzkj9g2ptayc2dzsiyhbjtlvfnje54mzz649gtwqvihan5fzv8vs3jl3kf9wb0br9ebr07qrfglwcvkkgktmtfds/4qqgywn7tvq3eh6hwqi7kuf0glz9cycyhki4/f61s6h9hws cprhchgfjmhnu 835dsvs4ijona 0s5jxwven/is5i5cmxfb3ruyzbfpu 7jldgcxlc8onkizxse1axhofmj4cttycyrxkncd015fnbmkh 7tyheksyyybtvjkpqdeczgt3z qvj9vdyuzb1q==", "sign": "d3b36e7a837d6241445e506faf72c8d8e3467ee9c11efae0c67dfb5b15f44b6e" }
接收后,先拿到密文,加入约定好的盐进行验签,验签通过后再用私钥进行解密。返回报文同理,只不过返回报文用的也是对方的公钥加密,对方接收后用自己的私钥解密。
demo:rsasha256test
jsondata = new hashmap<>();\n\n string publickey = \"miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeauazymb25s/ueifwmm2h74736dqqe4bvrdgnfwltm4pzdunc84ntav41qegbztby47o57m/ydvf6vmxjh25ejlsbbhls7fd7xhtkorskzqlekh0xcs2xa/akdwllbewunzvwmuqy8x3j2vnrilxzvjvqyxkfy0itmo8fq1xso6b/s5/raekpttiepfb2ciu9vmrtlocsnjvotupdwcoc79lts0g1q5bv4dn+uca+8/gubhs7vbth3olzt6gxtrjjrpxht4lqwsczqwkqhpg/8jqgnfqs7+r0kcyemg/411iazi9wyrgtsqji8sq2q7halzrxvjn+as7jjpvyi67jgkwidaqab\";\n string privatekey = \"miievqibadanbgkqhkig9w0baqefaascbkcwggsjageaaoibaqc5rpkyhbmz+54h/awzyfvjvfp1bathu9eoa19aw0zg/n240lzie1q/jwosbtm1vljs7nub9gnv/q8xckfbl6owweggwzsupvedoq6uyrmot6qftekzbfr9qr3cwvt7bq3o9yy5dlxfepzwesgtfnwo+pjgqvjsk0yjx+rxfi7oh9ln9fp4qlo0h6kuhzwht28yu0ugkyenwho491zyglv0u1lsdvdkfxh2f5rxr7z+bruflu9u2hegtm3qbdngmms/gfpiwpawjmrcrac8b/wlcccwqzv5hqpzj6yb/jxuhpkj1zhezoxcolyxdarsccvlfe8mf4czumk+/klrskyragmbaaecggeabjc+8dvj4j1n+2iu4g2tqt2pqsf+lcx/3tc7+b49jo8puuucvwy3znuhktkzrxzisxv2aralslnicgswyrreigmmjb00jgs/llm/sxkhwxmt7iezxbmjuvtnc7jy+3qcrti+9vh4w1kehaqb8opl8hvobiu3m2kglog20a7sym5gpicub3eq6p30u47y7i2wsbmnmmu79rpu3q7lsneob9kdvv6ea6vukl3chy1qxfh6ofzs1ynjfjxy5rxt8u5juhr5lyrnop8mevptbtrh34ssm0uyckkgj6josrdjqo/dj**xixj+bwgg5/xbnq3pfeyeaqkrtzy+fmhsufoaqkbgqdpqpxpl05mduxcnc7i6f8lzqjnjzu1h9zwkuqe94fs3i3siws62sjx1pz66p9eeiost0t4ye9ndx2x04yyfucenhydftq5m5m9e2q1kkdnebut6xy4wcribkozuq07mlysn0kdbuimp/erp2w3hl5nzu/elkdjt7ym0otv3upp5wkbgqdlbyc4hcvk+f1kd/xjq2ljwf+c8khhfrllripf7qtb24dcrauwxbagbbckxx2g+3waswyf09ndaliwab/juuuhjm0ygxyr0k5lhci0/ec7hd3twtl/hryef3umkzekbqypzneyme6t0lsqjl3mxfqlqumu4h677qa9/dnh7dyhhqkbgqcfam/bj6s7iba6jvfmozpi91bkvraawlgbxl7nt/nu0ncgzc0vd6wxgj3hqorgltu0krfv8pfp45qkphnwga8xd5gduiw68500zum8chdygeqejvvjvnuhqfnfexmirpfjnpqkcnrqxwk5cvmtci7+ys/fw0uwddivamcbn4auawkbgcogvaivnk6wefeeqqtsl6uozjaypbionek4src2fpinmdnlgmyvbmm51/lzealqa5p6fv2ipd4gae4nmznew+4qprswgudk3+ijw1sfk7qdwkzpeivpvddawyeshb8a22tpwwvae5er3m459avup8ubvw4rodxd4ka6gu1fh31paogaynpkjncrdosqh0nkh0ld44ch6hd+zcztoad2eqk0t2spnkbsis1s9w0adreoxuv1edo/hn3p/bctucaax7ijtscs2f0atc/nia6ljbnk7oubbzib9v21l72zvz5st4c/h7izbqcxfs81489a7tthp+e1hzs/xepfto0pakr1gj0=\";\n\n string salt = \"e4bvrdg\";\n system.out.println(\"公钥为:\" + publickey);\n string plaintext = \"{'a':'1111','b':'2222'}\";\n string ciphertext = null;\n string sign = null;\n try {\n ciphertext = rsautil.encrypt(plaintext,publickey);\n jsondata.put(\"data\",ciphertext);\n system.out.println(\"第一步,使用对方的rsa公钥对明文进行加密,得到的密文进行base64编码,作为data:\"+jsondata.get(\"data\"));\n sign = sha256util.getsha256str(ciphertext+salt);\n jsondata.put(\"sign\",sign);\n system.out.println(\"第二步,将data的值加上约定好的盐,使用sha256算法进行签名,得到的签名是16进制的串,放到sign:\"+jsondata.get(\"sign\"));\n\n } catch (exception e) {\n system.out.println(\"加密失败\");\n throw new runtimeexception(e);\n }\n system.out.println(\"得到的密文和签名为:\"+jsondata);\n system.out.println(\"模拟另一方收到密文和签名之后..........\");\n system.out.println(\"私钥为:\" + privatekey);\n string ciphertext1 = jsondata.get(\"data\");\n string sign1 = jsondata.get(\"sign\");\n string deciphering1 = null;\n if(sign1.equals(sha256util.getsha256str(ciphertext1+salt))){\n system.out.println(\"签名验证成功\");\n deciphering1 = rsautil.decrypt(ciphertext1,privatekey);\n system.out.printf(\"数据解密成功,data值为:\"+deciphering1);\n\n }else{\n system.out.println(\"签名验证失败,解密失败\");\n }\n\n }\n}\n\n\n\n","classes":null}" data-cke-widget-keep-attr="0" data-cke-widget-upcasted="1" data-widget="codesnippet">package rsasha256; import java.util.hashmap; import java.util.map; public class rsasha256test { public static void main(string[] args) { mapjsondata = new hashmap<>(); string publickey = "miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeauazymb25s/ueifwmm2h74736dqqe4bvrdgnfwltm4pzdunc84ntav41qegbztby47o57m/ydvf6vmxjh25ejlsbbhls7fd7xhtkorskzqlekh0xcs2xa/akdwllbewunzvwmuqy8x3j2vnrilxzvjvqyxkfy0itmo8fq1xso6b/s5/raekpttiepfb2ciu9vmrtlocsnjvotupdwcoc79lts0g1q5bv4dn uca 8/gubhs7vbth3olzt6gxtrjjrpxht4lqwsczqwkqhpg/8jqgnfqs7 r0kcyemg/411iazi9wyrgtsqji8sq2q7halzrxvjn as7jjpvyi67jgkwidaqab"; string privatekey = "miievqibadanbgkqhkig9w0baqefaascbkcwggsjageaaoibaqc5rpkyhbmz 54h/awzyfvjvfp1bathu9eoa19aw0zg/n240lzie1q/jwosbtm1vljs7nub9gnv/q8xckfbl6owweggwzsupvedoq6uyrmot6qftekzbfr9qr3cwvt7bq3o9yy5dlxfepzwesgtfnwo pjgqvjsk0yjx rxfi7oh9ln9fp4qlo0h6kuhzwht28yu0ugkyenwho491zyglv0u1lsdvdkfxh2f5rxr7z bruflu9u2hegtm3qbdngmms/gfpiwpawjmrcrac8b/wlcccwqzv5hqpzj6yb/jxuhpkj1zhezoxcolyxdarsccvlfe8mf4czumk /klrskyragmbaaecggeabjc 8dvj4j1n 2iu4g2tqt2pqsf lcx/3tc7 b49jo8puuucvwy3znuhktkzrxzisxv2aralslnicgswyrreigmmjb00jgs/llm/sxkhwxmt7iezxbmjuvtnc7jy 3qcrti 9vh4w1kehaqb8opl8hvobiu3m2kglog20a7sym5gpicub3eq6p30u47y7i2wsbmnmmu79rpu3q7lsneob9kdvv6ea6vukl3chy1qxfh6ofzs1ynjfjxy5rxt8u5juhr5lyrnop8mevptbtrh34ssm0uyckkgj6josrdjqo/dj**xixj bwgg5/xbnq3pfeyeaqkrtzy fmhsufoaqkbgqdpqpxpl05mduxcnc7i6f8lzqjnjzu1h9zwkuqe94fs3i3siws62sjx1pz66p9eeiost0t4ye9ndx2x04yyfucenhydftq5m5m9e2q1kkdnebut6xy4wcribkozuq07mlysn0kdbuimp/erp2w3hl5nzu/elkdjt7ym0otv3upp5wkbgqdlbyc4hcvk f1kd/xjq2ljwf c8khhfrllripf7qtb24dcrauwxbagbbckxx2g 3waswyf09ndaliwab/juuuhjm0ygxyr0k5lhci0/ec7hd3twtl/hryef3umkzekbqypzneyme6t0lsqjl3mxfqlqumu4h677qa9/dnh7dyhhqkbgqcfam/bj6s7iba6jvfmozpi91bkvraawlgbxl7nt/nu0ncgzc0vd6wxgj3hqorgltu0krfv8pfp45qkphnwga8xd5gduiw68500zum8chdygeqejvvjvnuhqfnfexmirpfjnpqkcnrqxwk5cvmtci7 ys/fw0uwddivamcbn4auawkbgcogvaivnk6wefeeqqtsl6uozjaypbionek4src2fpinmdnlgmyvbmm51/lzealqa5p6fv2ipd4gae4nmznew 4qprswgudk3 ijw1sfk7qdwkzpeivpvddawyeshb8a22tpwwvae5er3m459avup8ubvw4rodxd4ka6gu1fh31paogaynpkjncrdosqh0nkh0ld44ch6hd zcztoad2eqk0t2spnkbsis1s9w0adreoxuv1edo/hn3p/bctucaax7ijtscs2f0atc/nia6ljbnk7oubbzib9v21l72zvz5st4c/h7izbqcxfs81489a7tthp e1hzs/xepfto0pakr1gj0="; string salt = "e4bvrdg"; system.out.println("公钥为:" publickey); string plaintext = "{'a':'1111','b':'2222'}"; string ciphertext = null; string sign = null; try { ciphertext = rsautil.encrypt(plaintext,publickey); jsondata.put("data",ciphertext); system.out.println("{banned}中国第一步,使用对方的rsa公钥对明文进行加密,得到的密文进行base64编码,作为data:" jsondata.get("data")); sign = sha256util.getsha256str(ciphertext salt); jsondata.put("sign",sign); system.out.println("第二步,将data的值加上约定好的盐,使用sha256算法进行签名,得到的签名是16进制的串,放到sign:" jsondata.get("sign")); } catch (exception e) { system.out.println("加密失败"); throw new runtimeexception(e); } system.out.println("得到的密文和签名为:" jsondata); system.out.println("模拟另一方收到密文和签名之后.........."); system.out.println("私钥为:" privatekey); string ciphertext1 = jsondata.get("data"); string sign1 = jsondata.get("sign"); string deciphering1 = null; if(sign1.equals(sha256util.getsha256str(ciphertext1 salt))){ system.out.println("签名验证成功"); deciphering1 = rsautil.decrypt(ciphertext1,privatekey); system.out.printf("数据解密成功,data值为:" deciphering1); }else{ system.out.println("签名验证失败,解密失败"); } } }
生成一个对称算法秘钥,使用该秘钥对明文进行加密,然后将该秘钥使用对方的公钥进行加密,加密后编码,然后再对明文使用自己的私钥进行签名,因为私钥只有自己有,所以用自己的私钥签名后,对方使用你提供的公钥进行验签,就可以验证你的身份。
步骤:
1. 随机生成一个sm4密钥;
2. 使用sm4密钥加密密文,得到的密文进行base64编码,作为texttodecrypt
3. 将sm4密钥进行base64编码后,再使用对方的sm2公钥对这个base64串进行加密,得到的密文进行base64编码,作为keyciphertext;
4. 对第二步的明文使用第三方sm2私钥签名,得到的签名进行base64编码后作为signature。
加密后json:
{ "texttodecrypt": "cu0ymfmho3hxmvq0hwdhvzg9olsuzt19glbkcvhzdz4=", "signature": "meucia8no1g705b3zzmayv7yk8jajz9r2fkuvspzliy8k1xbaiea0noaeibos3fu7rwet81jtjwlrql tbqfy77vk/h/es4=", "keyciphertext": "bjv91ulad6fnchtkf/ b1jw2o7il0hjbr6erqry96s8qrdrke7y6epgzm/ey1oumnsr6vbruk0wx6yo8fq3qapyhzu5x1lzjgymc aicnhzut5v3xxz4yd0m1zx2d4ljaonjtded4ns5ku2 c5vff81dyzvdmww6zq==" }
对方接收后,按照以上步骤再进行验签,解密等操作。
demo:gmsmtest
jsondata = new hashmap<>();\n byte[] keyb = sm4util.generatekey(null);\n string key = base64.getencoder().encodetostring(keyb);\n string algorithmname = (\"sm4/ecb/pkcs5padding\");\n\n system.out.println(\"第一步,随机生成一个sm4秘钥:\"+key);\n system.out.println(\"选定算法:\"+algorithmname);\n\n // 用随机生成的sm4秘钥加密\n byte[] encryptmsg = sm4util.encrypt(algorithmname, keyb, null, messge.getbytes());\n jsondata.put(\"texttodecrypt\",base64.getencoder().encodetostring(encryptmsg));\n system.out.println(\"第二步,使用sm4密钥加密明文,得到的密文进行base64编码,作为texttodecrypt :\"+jsondata.get(\"texttodecrypt\"));\n\n // 将随机生成的sm4秘钥,使用对方的sm2公钥进行加密\n string keyciphertext = sm2util.encryptbysm2(key, otherpubk);\n jsondata.put(\"keyciphertext\",keyciphertext);\n system.out.println(\"第三步,将sm4密钥进行base64编码后,再使用对方的sm2公钥对这个base64串进行加密,得到的密文进行base64编码,作为 keyciphertext;\"+jsondata.get(\"keyciphertext\"));\n\n // 对明文使用自己的sm2私钥进行签名 如果有需要,可以加点盐\n string signature = sm2util.sign(prik,messge);\n jsondata.put(\"signature\",signature);\n system.out.println(\"第四步,对第二步的明文使用对方sm2私钥签名,得到的签名进行base64编码后作为 signature:\"+jsondata.get(\"signature\"));\n\n system.out.println(\"完整json串:\"+jsondata);\n\n // 模拟接到json传之后的处理\n // 对方拿到的,你的公钥,和对方自己的私钥\n string pubk = \"bntfr3oo1xm3bigoqqnk20qjfbfvk4hnfgs1dkzjuut9pw8i7k0d9l9p4mw+tqhwwfjld/nsx3by+orif1b25ba=\";\n string otherprik = \"i0shzcdm+os2fiahflxxkwji1abrhrxeys1axpztlnw=\";\n\n // 将sm4秘钥进行解密\n string keyciphertext1 = sm2util.decryptbysm2(jsondata.get(\"keyciphertext\"), otherprik);\n system.out.println(\"对方使用sm2私钥解密sm4秘钥:\"+keyciphertext1);\n\n // 通过sm4秘钥解密数据密文\n byte[] texttodecrypts = sm4util.decrypt(algorithmname, base64.getdecoder().decode(keyciphertext1), null, base64.getdecoder().decode(jsondata.get(\"texttodecrypt\").getbytes()));\n string texttodecryptss = new string(texttodecrypts);\n system.out.println(\"对方使用sm4秘钥解密后的数据:\"+ texttodecryptss);\n\n // 验证签名\n boolean proving = sm2util.verify(pubk, texttodecryptss, jsondata.get(\"signature\"));\n system.out.println(\"验证签名是否通过:\"+proving);\n\n\n }\n\n}\n\n\n\n","classes":null}" data-cke-widget-keep-attr="0" data-cke-widget-upcasted="1" data-widget="codesnippet">package gmsm; import java.util.hashmap; import java.util.map; import java.util.base64; public class gmsmtest { public static void main(string[] args) throws exception { // 你这边拿到的sm2公私钥,对方的公钥和自己的私钥 string prik = "amz5m/wogpgyixnlckc7 zdvzxnqymbcwxt1n7khfdvo"; string otherpubk = "bjkvgu87s7xhlrfci8mgpzp2x lizte 2so52cq1tveddqoe q4vdqxglv2jtiozewc/be8rzdo29svmtj8 7ma="; string messge = "{'aaa':'111','bbb':'222'}"; mapjsondata = new hashmap<>(); byte[] keyb = sm4util.generatekey(null); string key = base64.getencoder().encodetostring(keyb); string algorithmname = ("sm4/ecb/pkcs5padding"); system.out.println("{banned}中国第一步,随机生成一个sm4秘钥:" key); system.out.println("选定算法:" algorithmname); // 用随机生成的sm4秘钥加密 byte[] encryptmsg = sm4util.encrypt(algorithmname, keyb, null, messge.getbytes()); jsondata.put("texttodecrypt",base64.getencoder().encodetostring(encryptmsg)); system.out.println("第二步,使用sm4密钥加密明文,得到的密文进行base64编码,作为texttodecrypt :" jsondata.get("texttodecrypt")); // 将随机生成的sm4秘钥,使用对方的sm2公钥进行加密 string keyciphertext = sm2util.encryptbysm2(key, otherpubk); jsondata.put("keyciphertext",keyciphertext); system.out.println("第三步,将sm4密钥进行base64编码后,再使用对方的sm2公钥对这个base64串进行加密,得到的密文进行base64编码,作为 keyciphertext;" jsondata.get("keyciphertext")); // 对明文使用自己的sm2私钥进行签名 如果有需要,可以加点盐 string signature = sm2util.sign(prik,messge); jsondata.put("signature",signature); system.out.println("第四步,对第二步的明文使用对方sm2私钥签名,得到的签名进行base64编码后作为 signature:" jsondata.get("signature")); system.out.println("完整json串:" jsondata); // 模拟接到json传之后的处理 // 对方拿到的,你的公钥,和对方自己的私钥 string pubk = "bntfr3oo1xm3bigoqqnk20qjfbfvk4hnfgs1dkzjuut9pw8i7k0d9l9p4mw tqhwwfjld/nsx3by orif1b25ba="; string otherprik = "i0shzcdm os2fiahflxxkwji1abrhrxeys1axpztlnw="; // 将sm4秘钥进行解密 string keyciphertext1 = sm2util.decryptbysm2(jsondata.get("keyciphertext"), otherprik); system.out.println("对方使用sm2私钥解密sm4秘钥:" keyciphertext1); // 通过sm4秘钥解密数据密文 byte[] texttodecrypts = sm4util.decrypt(algorithmname, base64.getdecoder().decode(keyciphertext1), null, base64.getdecoder().decode(jsondata.get("texttodecrypt").getbytes())); string texttodecryptss = new string(texttodecrypts); system.out.println("对方使用sm4秘钥解密后的数据:" texttodecryptss); // 验证签名 boolean proving = sm2util.verify(pubk, texttodecryptss, jsondata.get("signature")); system.out.println("验证签名是否通过:" proving); } }
国密依赖pom
\n\t\n\t\t \n\tcom.google.guava \n\t\tguava \n\t\t30.1-jre \n\t\n\t\t \n\n\n","classes":null}" data-cke-widget-keep-attr="0" data-cke-widget-upcasted="1" data-widget="codesnippet">org.bouncycastle \n\t\tbcprov-jdk15on \n\t\t1.70 \n\tcom.google.guava guava 30.1-jre org.bouncycastle bcprov-jdk15on 1.70
凯发app官方网站 copyright 2001-2010 chinaunix.net all rights reserved 北京皓辰网域网络信息技术有限公司. 凯发k8官网下载客户端中心的版权所有