Public Static voidMain (string[] args) {Try{String plaintext= "Duwenlei"; Keypairgenerator Keypairgenerator= Keypairgenerator.getinstance ("RSA"); Keypairgenerator.initialize (2048); KeyPair KeyPair=Keypairgenerator.generatekeypair (); //SignatureMessageDigest MD = messagedigest.getinstance ("SHA1"); byte[] Enchash =md.digest (Plaintext.getbytes ()); Pkcs8encodedkeyspec KeySpec=NewPkcs8encodedkeyspec (Keypair.getprivate (). getencoded ()); Keyfactory keyfactory= Keyfactory.getinstance ("RSA"); Key Privatekey=keyfactory.generateprivate (KEYSPEC); Cipher ciphersign=cipher.getinstance (Keyfactory.getalgorithm ()); Ciphersign.init (Cipher.encrypt_mode,privatekey);//Ciphersign.init (Cipher.encrypt_mode,keypair.getprivate ()); byte[] Enchashsign =ciphersign.dofinal (Enchash); //VerificationX509encodedkeyspec Pkcs8encodedkeyspec =NewX509encodedkeyspec (Keypair.getpublic (). getencoded ()); Keyfactory keyfactorypub= Keyfactory.getinstance ("RSA"); Key PublicKey=keyfactorypub.generatepublic (PKCS8ENCODEDKEYSPEC); Cipher Cipherver=cipher.getinstance (Keyfactorypub.getalgorithm ()); Cipherver.init (Cipher.decrypt_mode, publickey);//Cipherver.init (Cipher.decrypt_mode, Keypair.getpublic ()); byte[] Dechashver =cipherver.dofinal (enchashsign); MessageDigest MD2= Messagedigest.getinstance ("SHA1"); byte[] Dechash =md2.digest (Plaintext.getbytes ()); //System.out.println ("Enchash =" + Byte2hex (Enchash));//System.out.println ("dechashver =" + Byte2hex (dechashver));//System.out.println ("Dechash =" + Byte2hex (Dechash));SYSTEM.OUT.PRINTLN ("The signature is correct:" +Byte2hex (dechashver). Equals (Byte2hex (Dechash))); Pemwriter Privatekeywriter=NewPemwriter (NewFileWriter (NewFile ("D://privatekey.key"))); Privatekeywriter.writeobject (Keypair.getprivate ()); Privatekeywriter.flush (); Privatekeywriter.close (); Pemwriter Publickeywriter=NewPemwriter (NewFileWriter (NewFile ("D://publickey.key"))); Publickeywriter.writeobject (Keypair.getpublic ()); Publickeywriter.flush (); Publickeywriter.close (); } 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 (); } Catch(invalidkeyspecexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } Public Static byte[] Hex2byte (String strhex) {if(Strhex = =NULL) { return NULL; } intL =strhex.length (); if(l% 2 = = 1) { return NULL; } byte[] B =New byte[L/2]; for(inti = 0; I! = L/2; i++) {B[i]= (byte) Integer.parseint (Strhex.substring (i * 2, I * 2 + 2), 16); } returnb; } Public StaticString Byte2hex (byte[] b) {String HS= ""; String stmp= ""; for(intn = 0; n < b.length; n++) {stmp= (java.lang.Integer.toHexString (b[n) & 0XFF)); if(stmp.length () = = 1) {HS= HS + "0" +stmp; } Else{HS= HS +stmp; } } returnhs.touppercase (); }
Java uses cipher to sign and verify