Using RSA, MD5 to generate signatures and checks on parameters

Source: Internet
Author: User
Tags md5 encryption tojson

In the daily work, we provide external interface or call the three-party interface is often a step to generate a signature or verification, this step is mainly to verify that the caller is

is not legal and whether the content has been modified. For example, for some web-based publicly downloaded software, videos, especially image files. If it is modified, it may result in

or other issues, the publisher image MD5 algorithm calculates a set of values. Let the downloaded user perform MD5 numerical comparison, that is, MD5 check. Due to the irreversible calculation of MD5 encryption,

If the value is the same, it means that the file has not been modified. Conversely, it has been modified.


Next through the text introduction, code, run the results of the way to introduce RSA, MD5 generated signature and verification;

First, the MD5 signature and the verification sign

1.MD5 Introduction

MD5 Full name Message-digest algorithm 5 (Information-Digest algorithm) is an irreversible encryption algorithm.

The MD5 algorithm has the following characteristics:

1, compressibility: Any length of data, calculated the length of the MD5 value is fixed.

2, easy to calculate: It is easy to calculate the MD5 value from the original data.

3, anti-modification: Any changes to the original data, even if only 1 bytes modified, the resulting MD5 value is very different.

4, strong anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, falsification of data).

MD5 generate signature and verification needs MD5 key, this key value is a string without any restrictions such as: 123456ADSEF

2. Signature and verification process

The first parameter is put into a string array signfields, the parameters and values are placed in an object or map, and the object is converted to a JSON object using Jsonobject.

Then constructs the signature original text, when constructs the signature original text, we need the parameter according to the dictionary (for example a,b,c) order, the concrete sorting method directly to the Java Arrays.sort method.

Then according to key=value all parameters and values are stitched into a string, a number of parameters directly separated by the "&" symbol, and then the MD5 key is spliced at the end of the original signature.

Finally, the signature is generated using Md5encrypt.getmessagedigest (SIGNSRC).

The verification is very simple, the verification party according to the signature process generated by the above signature and sent over the signature for comparison if the verification is successful, otherwise, the verification failed.

3. The specific code is as follows:

The parameter map to be checked:

Map<string,object> map=new hashmap<string,object> () map.put ("name", "Xiaoming"); Map.put ("Age", "n"); Map.put (" Sex "," male "), Map.put (" school "," xxx Secondary School "), Map.put (" Address "," xxx Community ");

MD5 Generate Signature string:

/** * MD5 Generate Signature String *  * @param map *            required Signature parameter * @param key *            Md5key * @return */public static string Md5sign (map< String, object> Map, String key) {string gensign = ""; try {string[] signfields = new String[5];signfields[0] = "name"; s IGNFIELDS[1] = "age"; signfields[2] = "sex"; signfields[3] = "school"; signfields[4] = "Address"; Jsonobject param = (jsonobject) jsonobject.tojson (map);//Generate signature Original String signsrc = Orgsignsrc (signfields, param);// MD5 Way Signature Signsrc + = "&key=" + key;gensign = md5encrypt.getmessagedigest (SIGNSRC);} catch (Exception e) {e.printstacktrace ();} return gensign;}


To build the original signature:

/** * Build Signature Original *  * @param signfilds parameter list * @param param parameter and value jsonbject * @return */private static String orgsignsrc (stri Ng[] signfields, jsonobject param) {if (signfields! = null) {Arrays.sort (signfields);//The key is sorted in dictionary order}stringbuffer SIGNSR c = new StringBuffer (""); int i = 0;for (String field:signfields) {signsrc.append (field); Signsrc.append ("="); Signsrc.app End (Stringutil.isempty (param.getstring (field))? "": param.getstring (field));//&if (I < (signfields.length-1)) {signsrc.append ("&") after the last element;} i++;} return signsrc.tostring ();}

MD5 Verifying signatures:

/** * MD5 Verification Signature * @param map * @param key * @param sign * @return */public static void Vlidatemd5sign (Map<string, object& Gt Map,string key,string sign) {String vsign=md5sign (map, key); System.out.println ("MD5 verify signature generated by signature:" +vsign); System.out.println ("MD5 verifies that the signature generated is consistent with the original signature: Sign=vsign True?false:" + (Vsign.equals (sign));}

Main method:

public static void Main (string[] args) {map<string,object> map=new hashmap<string,object> (); Map.put ("Name "," Xiao Ming "); Map.put (" Age "," Map.put "), Map.put (" school "," xxx Secondary School "), Map.put (" Address "," xxx Community "),/***MD5 signature and verification **/string key= "123456ADSEF"; String sign= md5sign (Map,key); System.out.println ("Generated MD5 signature:" +sign); vlidatemd5sign (map, key, sign);}

Execution Result:

Generated MD5 signature: A82ed0d0e0155d3926e0a6b6b3ee60c4md5 verifies signature generated by signatures: A82ED0D0E0155D3926E0A6B6B3EE60C4MD5 verifies that signatures are generated in the same signature as the original signature: sign =vsign True?false:true

ii. RSA signature and verification

1.RSA Introduction

RSA is currently the most influential public-key cryptography algorithm, based on a very simple number theory fact: it is easy to multiply two large primes, but then you want to

The factorization of the product is extremely difficult, so the product can be exposed as the encryption key, the public key, and the two large prime numbers combined into the private key. The public key is available for anyone to use,

The private key is owned by itself and is used for decryption. The decryption person has the private key, and the public key that is generated by the private key calculation is published to the cryptographic person. Encryption is encrypted using the public key and the ciphertext is sent

To the decryption, the decryption uses the private key decryption to decode the ciphertext into plaintext.

To send the information to B as an example, first determine the role: A for the encryption, and b for the decryption. First, b randomly identifies a key, called a key, that will always protect the key

In machine B instead of being sent out; then, the key is computed as a key, called the public key. The characteristic of this public key is that it is almost impossible to calculate the private key generated by it itself.

Next through the network to pass this public key to a, a received public key, the use of public key to encrypt the information, and the ciphertext sent to B through the network, and finally b using the known private key, the ciphertext into

The line is decoded. The above is the work flow of RSA algorithm.

2. Generate signature and verification process

Generate signer: First put the parameter into a string array signfields, put the parameters and values into an object or map, use Jsonobject to convert the object into a JSON object.

Then constructs the signature original text, when constructs the signature original text, we need the parameter according to the dictionary (for example a,b,c) order, the concrete sorting method directly to the Java Arrays.sort method. Then use RSA

's private key to sign the original signature.

Verification Party: As with the production of the signatory, Mr. Cheng signed the original text, then uses the RSA's public key, generates the signed party incoming signature and the signature source to verify the signature

The certificate result is true to verify that the validation was successful, otherwise failed.

3. Specific code implementation

Note: Generating public and private keys can use RSA related tools also can use online web tools, online tools a lot of, a search out. I am using: http://web.chacuo.net/netrsakeypair this online tool. I'm using a key length of 1024.


The parameter map to be checked:

Map<string,object> map=new hashmap<string,object> () map.put ("name", "Xiaoming"); Map.put ("Age", "n"); Map.put (" Sex "," male "), Map.put (" school "," xxx Secondary School "), Map.put (" Address "," xxx Community ");
RSA public Key and private Yue:

String prikey= " Miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbaoq30rck7l3fshhvywjk59sttogman7wfydrfn60amppyimcifxe3zaxf7swnbaqopuz /xyr+oaxubk17byks/e2+ Xa74wdn2vnbc7cziggajp9tgn0qhytclbtc3pchcu8tvccrlvun2lzjdlbhhpbdbfxzsqx9vwtm2qjf2gcragmbaaecgyeashnz4axopktnrsfvbiz5tlsibn Jts4cds1ysvwfe5rzls45dna0yk2bukphdfhdli99dbo02fdbzco5lke+zlehac/wtp6guee7jj5dwml3shbzmgitctk1/mq46ggrg4rradbqt /y7tenp/gf3y9ojyj+lmhfvfdejsuy1/qzecqqd6akqyfo8wuhlhy1ftvjmwlzok0szt9wtp+l6e7ct9+csvdwayjjrgsr6kuv+ 6yuwiesj41lvtgnry1oxeqg2takea7/v35kyg+fmwyq/dorbnaomrqgjvaolzgrok2dkjakpouafzk4ttq0kdjj3t6mzf/6iqy+ 1ofdd42knkjklfcqjariya0i/bsc4vki3rurcurum8e6g3orcym1d8syd10mh1/qfakfqnu+ 23m1lflr4jne34iscxpbgr3jrdtdfqxqjaxgwrkghz800tru3xmltiullmd6zp38qnoswwgmgk7sfyjzs//opp+q3n4v4qfedxaz4vy+ fhazpzf7smbkpzeqjallmakkeqkvpr8abxsrjw8u6s8thahx6crv/1fgdx1bkubyqdfmo5cqihn7isk2dhxi42bjvz63/d2aax3ltbka== "; String pubkey= "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdqt9k3joy9xbir1wfisufbe06bjaj+1n2haxtetajjz8ojhcbv3t2qmx+ 0ljw2kdj1m/8wk/qaf1aste28Pevxnvl2u+mhtdltw3o3gsiiaiz/brjdkowe3jw7qt6xixfpe1xhk5vvddpcyqywr4twqwrv87emfvclztqo39hnkwidaqab "; 
To generate an RSA signature string:

/** * RSA Generate Signature String *  * @param map *            required Signature parameter * @param prikey *            RSA private key * @return */public static string Rsasign (MAP&L T String, object> Map, String prikey) {string gensign = ""; try {string[] signfields = new String[5];signfields[0] = "Name "; signfields[1] =" age "; signfields[2] =" sex "; signfields[3] =" school "; signfields[4] =" Address "; Jsonobject param = (jsonobject) jsonobject.tojson (map);//Generate signature Original string src = orgsignsrc (signfields, param); gensign = Rsau Til.sign (SRC, prikey);} catch (Exception e) {e.printstacktrace ();} return gensign;}


To build the original signature:

/** * Build Signature Original *  * @param signfilds parameter list * @param param parameter and value jsonbject * @return */private static String orgsignsrc (stri Ng[] signfields, jsonobject param) {if (signfields! = null) {Arrays.sort (signfields);//The key is sorted in dictionary order}stringbuffer SIGNSR c = new StringBuffer (""); int i = 0;for (String field:signfields) {signsrc.append (field); Signsrc.append ("="); Signsrc.app End (Stringutil.isempty (param.getstring (field))? "": param.getstring (field));//&if (I < (signfields.length-1)) {signsrc.append ("&") after the last element;} i++;} return signsrc.tostring ();}

RSA Authentication Signature:

/** * RSA Verification Signature * @param map to participate in verification parameters * @param sign signer's incoming signature * @param publickey public key * @return */public static String vlidaters Asign (map<string, object> Map, String sign,string publickey) {string gensign = ""; try {string[] signfields = new STR Ing[5];signfields[0] = "name"; Signfields[1] = "age"; signfields[2] = "sex"; signfields[3] = "school"; signfields[4] = " Address "; Jsonobject param = (jsonobject) jsonobject.tojson (map);//Generate signature Original String signsrc = Orgsignsrc (signfields, param);// Call Tool class Verification Boolean bool = Rsautil.verify (SIGNSRC, sign, publickey); System.out.println ("Verify that signature is generated in accordance with the original signature: True?false:" + bool);} catch (Exception e) {e.printstacktrace ();} return gensign;}


Main method:

public static void Main (string[] args) {map<string,object> map=new hashmap<string,object> (); Map.put ("Name "," Xiao Ming "); Map.put (" Age "," Map.put "), Map.put (" school "," xxx Secondary School "), Map.put (" Address "," xxx Community "),/***rsa signature and verification **/string prikey= " Miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbaoq30rck7l3fshhvywjk59sttogman7wfydrfn60amppyimcifxe3zaxf7swnbaqopuz /xyr+oaxubk17byks/e2+ Xa74wdn2vnbc7cziggajp9tgn0qhytclbtc3pchcu8tvccrlvun2lzjdlbhhpbdbfxzsqx9vwtm2qjf2gcragmbaaecgyeashnz4axopktnrsfvbiz5tlsibn Jts4cds1ysvwfe5rzls45dna0yk2bukphdfhdli99dbo02fdbzco5lke+zlehac/wtp6guee7jj5dwml3shbzmgitctk1/mq46ggrg4rradbqt /y7tenp/gf3y9ojyj+lmhfvfdejsuy1/qzecqqd6akqyfo8wuhlhy1ftvjmwlzok0szt9wtp+l6e7ct9+csvdwayjjrgsr6kuv+ 6yuwiesj41lvtgnry1oxeqg2takea7/v35kyg+fmwyq/dorbnaomrqgjvaolzgrok2dkjakpouafzk4ttq0kdjj3t6mzf/6iqy+ 1ofdd42knkjklfcqjariya0i/bsc4vki3rurcurum8e6g3orcym1d8syd10mh1/qfakfqnu+ 23m1lflr4jne34iscxpbgr3jrdtdfqxqjaxgwrkghz800tru3xmltiullmd6zp38qnoswwgmgk7sfyjzs//opp+q3n4v4qfedxaz4vy+ Fhazpzf7smbkpzeqjallmakkeqkvpr8abxsrjw8u6s8thahx6crv/1fgdx1bkubyqdfmo5cqihn7isk2dhxi42bjvz63/d2aax3ltbka== "; String pubkey= "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdqt9k3joy9xbir1wfisufbe06bjaj+1n2haxtetajjz8ojhcbv3t2qmx+ 0ljw2kdj1m/8wk/qaf1aste28pevxnvl2u+mhtdltw3o3gsiiaiz/ Brjdkowe3jw7qt6xixfpe1xhk5vvddpcyqywr4twqwrv87emfvclztqo39hnkwidaqab "; String rsasign= rsasign (Map,prikey); SYSTEM.OUT.PRINTLN ("Generated RSA Signature:" +rsasign); vlidatersasign (map, rsasign, PubKey);}
Execution Result:

Generated RSA Signature: 6aff1e6a6ce17516d56ed94999e24fc6169290e111e207c4d9efa57da04525d173032fe32b620d16335164226420d0edee5ee5f9c9b413da f2b7f418ae4ea17e055d718b1c1cb188a9bbbe1c5cf559c0bd5cadf83468d62c29635ef7cde6b6af0d63137a8fda3cb26996dfba3c505edc04a843224 AD1BBCA34ACD80EF7C3C5CA Verify that the signature generated by the signature is consistent with the original signature: True?false:true


The above is MD5, RSA signature and verification of the introduction.

Note: For the Md5encrypt, Rsautil class files and related jar packages used in this article, it is written here because of more code. I directly to the demo source upload to my space, you can download for free. The address is as follows:

http://download.csdn.net/detail/mr_smile2014/9596252




Using RSA, MD5 to generate signatures and checks on parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.