Important things to say three times, this article is mainly to verify the Java RSA Signature, verification test code, the main code reference http://xw-z1985.iteye.com/blog/1837376
Important things to say three times, this article is mainly to verify the Java RSA Signature, verification test code, the main code reference http://xw-z1985.iteye.com/blog/1837376
Important things to say three times, this article is mainly to verify the Java RSA Signature, verification test code, the main code reference http://xw-z1985.iteye.com/blog/1837376
Below is the C # version of RSA, DSA code
Using System.Security.Cryptography; public class asymmetricalgorithmhelper<t> where t:asymmetricalgorithm, new () {protected static T Result execute<tresult> (String key, Func<t, tresult> Func) {using (T algorithm = new T ()) {algorithm. Fromxmlstring (key); return func (algorithm); }}///<summary>///Generate public key, private key by default rule///</summary>//<param name= "Publi Ckey "> Public key (XML format) </param>//<param name=" Privatekey "> Private key (XML format) </param> publicly static VO ID Create (out string publickey, out string privatekey) {keygenerator.createasymmetricalgorithmkey<t& gt; (out PublicKey, out privatekey); }} public class Rsahelper:asymmetricalgorithmhelper<rsacryptoserviceprovider> {//<SUMMARY&G T RSA encryption//</summary>//<param name= "PublicKey "> Public key </param>//<param name=" Content "> Original data before encryption </param>///<param name=" FO AEP "> If True, direct System.Security.Cryptography.RSA encryption is performed using OAEP padding (available only on computers running Microsoft Windows XP or later); False, the PKCS#1 version 1.5 is used to populate. </param>///<returns> Encrypted results (base64 format) </returns> public static string Encrypt (String publi Ckey, string content, bool FOAEP = False) {return Execute (publickey, algorithm = Con Vert. ToBase64String (algorithm. Encrypt (Encoding.UTF8.GetBytes (content), FOAEP)); }//<summary>//RSA decryption///</summary>/<param name= "Privatekey" > Private key < /param>//<param name= "Content" > Encrypted contents (base64 format) </param>//<param name= "FOAEP" > If True to perform direct System.Security.Cryptography.RSA encryption using OAEP padding (available only on computers running Microsoft Windows XP or later), otherwise, if false, use pkcs# 1 version 1.5 fill. </param>//<returns></returns> public static string Decrypt (string Privatekey, string content, bool FOAEP = False) {return Execute (privatekey, algorithm = Encoding.UTF8.GetString (algorithm. Decrypt (convert.frombase64string (content), FOAEP)); }//<summary>//RSA signature///</summary>//<param name= "Privatekey" > Private key < /param>//<param name= "Content" > Original data to be signed (UTF-8) </param>//<param name= "Halg" > The calculation of the signature method, if NULL, uses the MD5 algorithm </param>////<returns> signed value (base64 format) </returns> public static string Sig Ndata (string Privatekey, string content, Object halg = null) {return Execute (Privatekey, Algorithm = convert.tobase64string (algorithm. SignData (Encoding.UTF8.GetBytes (content), Gethalg (HALG))); }//<summary>//RSA check-in///</summary>//<param name= "PubliCkey "> Public key </param>//<param name=" Content "> Verification of Signed data (UTF-8) </param>//<param name=" Signature "> Signature string to be validated (base64 format) </param>//<param name=" Halg "> Signature adoption algorithm, if NULL, MD5 algorithm </param& Gt <returns></returns> public static bool Verifydata (string publickey, string content, String Signatur E, Object halg = null) {return Execute (publickey, algorithm = algorithm. Verifydata (Encoding.UTF8.GetBytes (content), Gethalg (Halg), convert.frombase64string (signature)); } private static Object Gethalg (object Halg) {if (Halg = = null) {Halg = "MD5"; } return halg; }///<summary>//Generate public key, private key///</summary>//<param name= "PublicKey" > Public key (Xm L format) </param>//<param name= "Privatekey" > Private key (XML format) </param>//<param name= "KEysize "> KeySize to be generated, supported minsize:384 maxsize:16384 skipsize:8</param> public static void Create (out string p Ublickey, out string privatekey, int keySize = 1024x768) {RSACryptoServiceProvider Provider = new Rsacrypto ServiceProvider (keySize); Keygenerator.createasymmetricalgorithmkey (out PublicKey, out privatekey, provider); }} public class Dsahelper:asymmetricalgorithmhelper<dsacryptoserviceprovider> {//<summary& Gt DSA Signature///</summary>//<param name= "Privatekey" > Private key </param>//<param name = "Content" > Original data to be signed (UTF-8) </param>//<returns> signed value (base64 format) </returns> public static String SignData (String Privatekey, string content) {return Execute (Privatekey, Algorith m = convert.tobase64string (algorithm. SignData (Encoding.UTF8.GetBytes (content))); }//<summary>DSA check-in//</summary>//<param name= "PublicKey" > Public key </param>//<param name= "Content" > required verification of signed data (UTF-8) </param>//<param name= "signature" > Signature string to be validated (base64 format) </param> <returns></returns> public static bool Verifydata (string publickey, string content, String Signa ture) {return Execute (publickey, algorithm = algorithm. Verifydata (Encoding.UTF8.GetBytes (content), convert.frombase64string (signature))); }///<summary>//Generate public key, private key///</summary>//<param name= "PublicKey" > Public key (Xm L format) </param>//<param name= "Privatekey" > Private key (XML format) </param>//<param name= "KeySize" &G t; KeySize to be generated, supported minsize:512 maxsize:1024 skipsize:64</param> public static void Create (out string publickey, Out string privatekey, int keySize = 1024x768) {DsacryptoserviceproviDer Provider = new DSACryptoServiceProvider (keySize); Keygenerator.createasymmetricalgorithmkey (out PublicKey, out privatekey, provider); } }
Test code under C #
static void Rsademo () {string publicjavakey, Privatejavakey, Content, Publiccsharpkey, Privatec Sharpkey, SignData; Java base64 format Key Privatejavakey = "Miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbamsnfzumkwtwfh271jmbjumsll2 c4dw5iyps/jkxu5vxhyznakma5bu2adlhw2fza/fapglwdn68/8og1vex0m9c/5yhigsidhzixi6wrkmffqp/ nzhcrgcm900p0um1waceempevu7+ Uq9bsrmjwxwsmcryp63kktczcffw05u9agmbaaecgybiiisctp8ihglkbddimqtiaepvde0rluizkgkgeof2q6kvbs6llsro73pnqjj3vpq89sl8cn52miua4 daqefwjgtl/cy2rkk64ajeszadiqnw2f2whsuob/ t1wev05jqeej4qudvp5yz1lhwvwlwob3blwpwhnreg87os8jffqlqjbapea0kv1oihlqx1ew1weqd8mk2vbtmldowzl4uzvdkx7/ dtthvxnw25cvfjm6v9aet2j9jbyt2phibfjf1ficmmcqqdxr6+ Yfl7ylovdim4lqfh7if03gsjsfvizvuyoi6suumytfhjfkdyl3jm4flywdpfpn76b9tdpjaz4py1kfitfakbg0zd6vrljscfpb4gqzzmfsbgszsjnfyshdkge ssaqhzbxnduszgv5lpsc4orq3g60ietfwalhp6fma2lukba1akears3or+y5u/+aucbtrpfzijvoia89vrmwxtk4bks/ Fptwqqukca8xpidsoect1hr6tf33wofltxhhezoluwwixwjazq4fs9gatxyn+3ubxxltbykxpyhfwep1jviqqoactklxbjwoyzdnuo2jr6wz2ubeadcqza30vgmjg7pud94zha== "; Publicjavakey = " Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdldrwvjislcbr9u9stg47jljs9gua8oymkbp45f7ub8ywmzwijaoqbtghzycnhcwp32qyjvgzevp /dhtb3l9dpqv+wiyolchyc4syulq5dbx6qf52yxeyhjvdnd9fdncahhnpjxl1o/rqvw0qzcvscepnk8j+tyirqmxbx1tobvqidaqab "; Content = "test data hello"; Converted to C # XML Format Publiccsharpkey = Rsaconverter.rsapublickeyjava2dotnet (Publicjavakey); Privatecsharpkey = Rsaconverter.rsaprivatekeyjava2dotnet (Privatejavakey); Console.WriteLine ("Converted C # Public key:" + Publiccsharpkey); Console.WriteLine ("Convert the resulting C # private key:" + Privatecsharpkey); Rsahelper.create (out Publiccsharpkey, out Privatecsharpkey, 1024); String encdata = Rsahelper.encrypt (publiccsharpkey, content); Console.WriteLine ("Public Key Cryptography Result:" + encdata); Console.WriteLine ("Private key decryption Result:" + rsahelper.decrypt (Privatecsharpkey, encdata)); The following is a signature generated by Java through Sha1withrsa//dv67xt5sggq9q+bkvwuyyxljx28cxnkimdk5ro8cmopsipf7z8/n/02yan/svuqpmwjk/f+cjwydikvstwjkll49/d4prtw+ nd4xwr5hea8n7c6jtdrvaogwfg3do1n8sndj7aqxuuwumllic1dyehezhswm9bcmjjsvf8n34cy=//The following is a signature generated by Java through MD5WITHRSA muxpvxxnzolzdy03hoxqgqlqnj/srja0lxqax8kl+h+ plbcl6cqdlupvwk6mwkz1mrp2ccwgaqc8whkovrafpdkosrsnknkajrv1iqhbxjtpcg83xlrb7aofzqhi/vulca9kdwqmvnarvcv+ lvwwuvcxp5ck1nwejn258t/ev8m=//The following is a signature generated by Java through Sha256withrsa//QPFKIAITCKW452/NACSQHJNBBUTJNHEL4SPTMP1 t/ngay0z4i3xx13/avl001zkwbfdff7cipaklbqmywm3sqezvpbqlvoymzbarlhaooextczk50tgrcfulxxa2pwt+ jrs2lgux5esbo6cks0yk1fdkylm+4s4nrkygeaxo+ly= string halg = "SHA256";//sha1 MD5 SHA256 signdata = RSA Helper.signdata (Privatecsharpkey, Content, Halg);//sha1 Console.WriteLine ("Generate Signature:" + signdata); Console.WriteLine ("Signature consistent:" + rsahelper.verifydata (publiccsharpkey, Content, SignData, halg)); } static void Dsademo () {string publickey, Privatekey; DSahelper.create (out PublicKey, out privatekey); String content = "test data"; String signdata = Dsahelper.signdata (privatekey, content); Console.WriteLine ("Generate Signature:" + signdata); Console.WriteLine ("Signature consistent:" + dsahelper.verifydata (publickey, Content, SignData)); }
Then the Java version of the Code, note that the reference address code is basically the same, just adjust the hash algorithm passed, and also contains the test code
Import Java.io.bytearrayinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.stringwriter;import Java.security.keyfactory;import Java.security.nosuchalgorithmexception;import Java.security.privatekey;import Java.security.publickey;import Java.security.signature;import Java.security.signatureexception;import Java.security.spec.invalidkeyspecexception;import Java.security.spec.pkcs8encodedkeyspec;import Java.security.spec.x509encodedkeyspec;import Org.apache.commons.codec.binary.base64;import Org.apache.commons.io.ioutils;import Org.apache.commons.lang.stringutils;public class Test {private static String Privatekey = " miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbamsnfzumkwtwfh271jmbjumsll2c4dw5iyps/ jkxu5vxhyznakma5bu2adlhw2fza/fapglwdn68/8og1vex0m9c/5yhigsidhzixi6wrkmffqp/nzhcrgcm900p0um1waceempevu7+ Uq9bsrmjwxwsmcryp63kktczcffw05u9agmbaaecgybiiisctp8ihglkbddimqtiaepvde0rluizkgkgeof2q6kvbs6llsro73pnqjj3vpq89sl8cn52miua4 Daqefwjgtl/cy2rkk64ajeszadiqnw2f2whsuob/t1wev05jqeej4qudvp5yz1lhwvwlwob3blwpwhnreg87os8jffqlqjbapea0kv1oihlqx1ew1weqd8mk2vbtmldowzl4uzvdkx7/ dtthvxnw25cvfjm6v9aet2j9jbyt2phibfjf1ficmmcqqdxr6+ Yfl7ylovdim4lqfh7if03gsjsfvizvuyoi6suumytfhjfkdyl3jm4flywdpfpn76b9tdpjaz4py1kfitfakbg0zd6vrljscfpb4gqzzmfsbgszsjnfyshdkge ssaqhzbxnduszgv5lpsc4orq3g60ietfwalhp6fma2lukba1akears3or+y5u/+aucbtrpfzijvoia89vrmwxtk4bks/ fptwqqukca8xpidsoect1hr6tf33wofltxhhezoluwwixwjazq4fs9gatxyn+ 3ubxxltbykxpyhfwep1jviqqoactklxbjwoyzdnuo2jr6wz2ubeadcqza30vgmjg7pud94zha== ";p rivate static String PublicKey =" Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdldrwvjislcbr9u9stg47jljs9gua8oymkbp45f7ub8ywmzwijaoqbtghzycnhcwp32qyjvgzevp /dhtb3l9dpqv+wiyolchyc4syulq5dbx6qf52yxeyhjvdnd9fdncahhnpjxl1o/rqvw0qzcvscepnk8j+tyirqmxbx1tobvqidaqab "; private static String algorithm= "Sha256withrsa";//md5withrsa sha1withrsa sha256withrsapublic static void Main (string[] args) {Test run1 = new test (); try {String sign = run1.rsasign ("Test data Hello", Privatekey, "Utf-8", algorithm); System.out.println (siGN); Boolean bRet = Run1.docheck ("Test data Hello", sign, PublicKey, "Utf-8", algorithm); System.out.println (BRet);} catch (Signatureexception e) {e.printstacktrace ();}} public string Rsasign (string content, String Privatekey, String charset, String algorithm) throws Signatureexception {try {Privatekey Prikey = getPrivateKeyFromPKCS8 ("RSA", New Bytearrayinputstream (Privatekey.getbytes ())); Signature Signature = signature.getinstance (algorithm);//md5withrsa Sha1withrsa Sha256withrsasignature.initsign ( Prikey), if (Stringutils.isempty (charset)) {Signature.update (Content.getbytes ());} else {signature.update ( Content.getbytes (CharSet));} Byte[] signed = Signature.sign (); return new String (Base64.encodebase64 (Signed));} catch (Exception e) {throw new Signatureexception ("rsacontent =" + content + "; CharSet = "+ CharSet, E);}} Boolean Docheck (string content, string sign, String PublicKey, String charset, String algorithm) throws Signatureexception {try {PublicKey PubKey = getPublicKeyFromX509 ("RSA", New BytEarrayinputstream (Publickey.getbytes ())); Signature Signature = signature.getinstance (algorithm);//md5withrsa Sha1withrsa sha256withrsasignature.initverify ( PubKey); byte[] Encodedkey = Content.getbytes (charset); Signature.update (encodedkey);//Signature.update ( Getcontentbytes (content, CharSet)); return Signature.verify (Base64.decodebase64 (Sign.getbytes ()));} catch (Exception e) {throw new Signatureexception ("RSA authentication Signature [content =" + content + "; CharSet = "+ CharSet +"; Signature = "+ sign +"] An exception occurred! ", e);}} Private PublicKey getPublicKeyFromX509 (String algorithm, InputStream ins) throws NoSuchAlgorithmException {try { Keyfactory keyfactory = keyfactory.getinstance (algorithm); StringWriter writer = new StringWriter ();//Streamutil.io (new InputStreamReader (INS), writer);//byte[] Encodedkey = writ Er.tostring (). GetBytes (); byte[] Encodedkey = ioutils.tobytearray (INS);//base64 decode Encodedkey = Base64.decodebase64 ( Encodedkey); return Keyfactory.generatepublic (New X509encodedkeyspec (Encodedkey)); CaTCH (IOException ex) {//cannot occur} catch (Invalidkeyspecexception ex) {//cannot occur}return null;} Public Privatekey getPrivateKeyFromPKCS8 (String algorithm, InputStream ins) throws Exception {if (INS = = NULL | | Stringutils.isempty (algorithm)) {return null;} Keyfactory keyfactory = keyfactory.getinstance (algorithm); byte[] Encodedkey = ioutils.tobytearray (ins); EncodedKey = Base64.decodebase64 (Encodedkey); return keyfactory.generateprivate (New Pkcs8encodedkeyspec (Encodedkey));}}
RSA encryption, decryption, signature, verification, DSA signature, check