Original address: an example of Java digital signature based on RSA algorithm
First, preface:
Network data security includes the security of the data itself, the integrity of the data (to prevent tampering), the non-repudiation of the data source, and other elements. Encryption algorithm for data encryption can ensure the security of the data itself, the use of Message digest can guarantee the integrity of the data, but also a point is the data source of non-repudiation (that is, where the data from the receiver is clear, and the sender can not deny).
Some schemes have used message authentication codes (Macs) to ensure that data originates from legitimate senders, but the use of message authentication codes can create a problem in which both parties must agree to a shared password for the communication between the two. In our internet so huge today, this is obviously inappropriate, and digital signatures can solve our problem. A digital signature (typically a digital signature) is based on a public key cryptography (for example: RSA). The sender has a unique public and private key, the public key is public, and the private key is kept secret. The sender uses the private key to digitally sign the message digest of the data, and the receiver uses the sender's public key to verify the digital signature, in effect reversing the encryption process. Since the sender's private key is unique and secret, so when it is possible to verify that the digital digest that unlocks the digital signature is correct, then we can be sure of the sender's identity, which is the basic principle of digital signatures.
Why use a message digest? The reason is that, because the public key encryption algorithm and decryption speed is slow, the entire data encryption is certainly not feasible, and the message digest has a benefit is short and fixed length, like the fingerprint of the data, so the digest is signed.
Second, the principle of digital signature:
In a digital signature application, the sender's private key and public key are generated first, and then the data is encrypted by the sender through the private key, and the encrypted data is sent to the receiver, and the receiver encrypts the sender's encrypted data through the sender's common key for signature verification.
Third, the example shows:
Now we're going to get to the chase. The Java digital Signature class is encapsulated in the Signature class (Java.security.Signature).
Next, I'll write three functions (three Java classes):
A, generate a pair of keys, that is, the private key and the public key, for the preservation of the key can be used to save and transfer the object stream, or can be stored in an encoded way; I use encoding to save it here, based on convenience; the class name is: Generatekeypair.java
b, write the function of the sender: first encrypt the data to be output by the private key, and the output and data after the signature; the class name is: Signaturedata.java
c, write the function of the receiver: Use the sender's public key to verify the encrypted data sent over to determine the legitimacy of the signature; the class name is: Verifysignature.java
Four, generate a pair of keys, that is, the private key and the public key, the preservation of the key can be used to save and transfer the object stream, can also be stored in an encoded way; I use encoding to save it here, based on convenience; the class name is: Generatekeypair.java :
PackageCom._21cn.cryptto;ImportJava.security.KeyPair;ImportJava.security.PrivateKey;ImportJava.security.PublicKey;ImportJava.security.SecureRandom; Public classGeneratekeypair {PrivateString Prikey;PrivateString PubKey; Public voidrun () {Try{java.security.KeyPairGenerator keygen=Java.security.KeyPairGenerator.getInstance ("RSA"); SecureRandom Secrand=Newsecurerandom (); Secrand.setseed ("21CN". GetBytes ());//initializing the random generatorKeygen.initialize (1024, Secrand); KeyPair Keys=Keygen.genkeypair (); PublicKey PubKey=keys.getpublic (); Privatekey Prikey=keys.getprivate ();p Ubkey=Bytestohexstr (pubkey.getencoded ());p Rikey=Bytestohexstr (prikey.getencoded ()); System.out.println ("Pubkey=" +PubKey); System.out.println ("Prikey=" +Prikey); System.out.println ("Write Object Pubkeys OK"); System.out.println ("Generate Key pair Success");} Catch(java.lang.Exception e) {e.printstacktrace (); System.out.println ("Generate key pair failed");};}/*** Transform The specified byte into a Hex String form.*/ Public Static FinalString Bytestohexstr (byte[] BCD) {StringBuffer s=NewStringBuffer (Bcd.length * 2); for(inti = 0; i < bcd.length; i++) {s.append (bcdlookup[(bcd[i)>>> 4) & 0x0f]); S.append (Bcdlookup[bcd[i]& 0x0f]);}returns.tostring ();}/*** Transform The specified Hex String into a byte array.*/ Public Static Final byte[] hexstrtobytes (String s) {byte[] bytes;bytes=New byte[S.length ()/2]; for(inti = 0; i < bytes.length; i++) {Bytes[i]= (byte) Integer.parseint (s.substring (2 * I, 2 * i + 2),16);}returnbytes;}Private Static Final Char[] bcdlookup = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ',' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F ' };/*** @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubGeneratekeypair n =NewGeneratekeypair (); N.run ();}
Five, write the function of the sender: first encrypt the data to be output by the private key, and the output and data after the signature; the class name is: Signaturedata.java
PackageCom._21cn.cryptto;Importjava.security.KeyFactory;ImportJava.security.PrivateKey;ImportJava.security.spec.PKCS8EncodedKeySpec; Public classSignatureData { Public voidrun () {Try{String Prikeyvalue= "30820277020100300d";//This is the private key encoding of the Generatekeypair output.Pkcs8encodedkeyspec pripkcs8=NewPkcs8encodedkeyspec (Hexstrtobytes (Prikeyvalue)); Keyfactory Keyf=keyfactory.getinstance ("RSA"); Privatekey Myprikey=keyf.generateprivate (priPKCS8); String MyInfo= "orderid=10dkfadsfksdkssdkd&amount=80&ordertime=20060509";//the information to be signed//Generating digital signatures for information with the private keyJava.security.Signature signet =Java.security.Signature.getInstance ("Md5withrsa"); signet.initsign (Myprikey); Signet.update (Myinfo.getbytes ("Iso-8859-1"));byte[] signed = Signet.sign ();//Digital Signature of the informationSystem.out.println ("Signed (signature content) Original value =" +Bytestohexstr (signed)); System.out.println ("Info (original value) =" +MyInfo); System.out.println ("Signing and generating file success");} Catch(java.lang.Exception e) {e.printstacktrace (); System.out.println ("Signing and generating file failed");};}/*** Transform The specified byte into a Hex String form.*/ Public Static FinalString Bytestohexstr (byte[] BCD) {StringBuffer s=NewStringBuffer (Bcd.length * 2); for(inti = 0; i < bcd.length; i++) {s.append (bcdlookup[(bcd[i)>>> 4) & 0x0f]); S.append (Bcdlookup[bcd[i]& 0x0f]);}returns.tostring ();}/*** Transform The specified Hex String into a byte array.*/ Public Static Final byte[] hexstrtobytes (String s) {byte[] bytes;bytes=New byte[S.length ()/2]; for(inti = 0; i < bytes.length; i++) {Bytes[i]= (byte) Integer.parseint (s.substring (2 * I, 2 * i + 2),16);}returnbytes;}Private Static Final Char[] bcdlookup = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ',' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F ' };/*** @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubSignatureData s =NewSignatureData (); S.run ();}
Six, write the function of the receiver: Use the sender's public key to verify the encrypted data sent over, to determine the legitimacy of the signature; the class name is: Verifysignature.java
PackageCom._21cn.cryptto;Importjava.security.KeyFactory;ImportJava.security.PublicKey;ImportJava.security.spec.X509EncodedKeySpec; Public classVerifySignature { Public voidrun1 () {Try{String Pubkeyvalue= "30819f300d06092a864886f70d01010105";//This is the public key encoding of the Generatekeypair outputX509encodedkeyspec Bobpubkeyspec =NewX509encodedkeyspec (Hexstrtobytes (Pubkeyvalue)); Keyfactory keyfactory= Keyfactory.getinstance ("RSA"); PublicKey PubKey=keyfactory.generatepublic (BOBPUBKEYSPEC); String Info= "orderid=10dkfadsfksdkssdkd&amount=80&ordertime=20060519";byte[] signed = Hexstrtobytes ("2292E02BA6BF6F1B1688A6FA2");//This is the digital signature of the SignatureData output.Java.security.Signature signetcheck=java.security.signature.getinstance ("Md5withrsa"); signetcheck.initverify (PubKey); Signetcheck.update (Info.getbytes ());if(Signetcheck.verify (Signed)) {SYSTEM.OUT.PRINTLN ("Info=" +info); System.out.println ("Signature OK");}ElseSYSTEM.OUT.PRINTLN ("Non-signed normal");}Catch(java.lang.Exception e) {e.printstacktrace ();}}
An example of Java digital signature based on RSA algorithm