How to use RSA encryption algorithm to verify data in Android application development

Source: Internet
Author: User

The world is very exciting, the world is very helpless. Yes, in the age of the Internet, how to protect your data and how to encrypt and perform the data becomes very important. Here is a summary of the Android platform using the Java language, using the RSA algorithm to verify the data experience.

Let's take a look at how the RSA encryption algorithm verifies the data:

1, the first to use a program such as OpenSSH to generate a private key

2, then generate a public key according to the private key

3. Use the private key and public key to sign the data and get the signature file.

4. The data can be verified by using the public key and signature file.


Look again at how to achieve:

1. Generate a 2048-bit private key:

OpenSSL genrsa-out Private.pem 2048


2. Generate Public key

The use of OpenSSH can also generate a public key, but in the process of use, found that due to the format of the problem, the use of OpenSSH generated public key in Java always prompt exception, so in the end it is based on the relevant information on the Internet, using the Java language to write programs, The public key used can be used in Java, with the following code:

Genpublic.java

Import Java.io.bufferedreader;import Java.io.bytearrayoutputstream;import Java.io.dataoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.FileReader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.PrintStream; Import Java.math.biginteger;import Java.security.keyfactory;import Java.security.keypair;import Java.security.publickey;import Java.security.security;import Java.security.signature;import Java.security.interfaces.dsaparams;import Java.security.interfaces.dsapublickey;import Java.security.interfaces.rsapublickey;import Java.security.spec.x509encodedkeyspec;import Java.security.spec.rsapublickeyspec;import Javax.xml.bind.datatypeconverter;import Org.bouncycastle.jce.provider.bouncycastleprovider;import Org.bouncycastle.openssl.pemreader;import    Org.bouncycastle.util.encoders.base64;public class Genpublic {public static printstream out = System.out; public static PrIntstream err = System.err; private static void Genpublickey (String privatefile,string pubfile) {try {pemreader pemreader = new Pemrea        Der (New FileReader (Privatefile));        KeyPair pair = (KeyPair) pemreader.readobject ();        PublicKey PubKey = Pair.getpublic ();    FileOutputStream outpub = new FileOutputStream (pubfile);    byte[] bytes = Pair.getpublic (). getencoded ();    Outpub.write (bytes);        Outpub.close ();        } catch (Exception e) {e.printstacktrace (); }} public static void Main (string[] args) throws Exception {if (args.length! = 2) {err.println ("Usa            Ge:java genpublic <pem file> <public file> ");        System.exit (1);        } File Pemfile = new file (Args[0]);            if (!pemfile.exists ()) {err.println ("PEM File Does not Exist");        System.exit (1);        } security.addprovider (New Bouncycastleprovider ());    Genpublickey (Args[0],args[1]); }}


How to use:

Compile first:

Then use the compiled program to generate the public key:

Java genpublic Private.pem Public.bin


The libraries you use can be downloaded in the links at the end of this article.


Then take a look at the Java code that generated the signature file:

Sign.java


Import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.filereader;import Java.io.filewriter;import Java.io.IOException;import Java.io.printstream;import Java.security.keyfactory;import Java.security.keypair;import Java.security.keypairgenerator;import Java.security.publickey;import Java.security.securerandom;import Java.security.security;import Java.security.signature;import Java.security.spec.x509encodedkeyspec;import Javax.xml.bind.datatypeconverter;import Org.bouncycastle.jce.provider.bouncycastleprovider;import Org.bouncycastle.jce.provider.jdkkeypairgenerator;import Org.bouncycastle.openssl.pemreader;import  Org.bouncycastle.openssl.pemwriter;class Sign {public static printstream out = System.out;  public static PrintStream err = System.err;  private static byte[] Pubkeydata = null; public static void Main (string[] args) throws Exception {if (Args.length < 4) {err.println ("Usage:java JAvasign <pem file> <public file> <data file to sign> <signed file> ");    System.exit (1);    } File Pemfile = new file (Args[0]);    File Pubfile = new file (args[1]);        File datafile = new file (args[2]);    if (!datafile.exists ()) {err.println ("Data File Does not Exist");    System.exit (1);    } security.addprovider (New Bouncycastleprovider ());        KeyPair keys = null; if (!pemfile.exists ()) {err.println ("PEM File Does not Exist.    Generating. ");        Keypairgenerator r = keypairgenerator.getinstance ("RSA");    KeySize in bits is 2048 r.initialize (2048,new securerandom ());    Keys = R.generatekeypair ();    Pemwriter pemwriter = new Pemwriter (new FileWriter (Pemfile));    Pemwriter.writeobject (keys); Pemwriter.close (); You must flush or close the file or else it'll not save} else {keys = (KeyPair) New Pemreader (New Filereade    R (Pemfile)). ReadObject (); }//read data file into signature instance FiLeinputstream fin = new FileInputStream (datafile);    byte[] data = new byte[(int) datafile.length ()];    Fin.read (data);        Fin.close ();    Sign the data Signature SG = signature.getinstance ("Sha1withrsa");    Sg.initsign (Keys.getprivate ());        Sg.update (data);        Output Base64 encoded binary signature byte signbytes[] = Sg.sign ();    Fin = new FileInputStream (pubfile);    Pubkeydata = new byte[(int) pubfile.length ()];    Fin.read (Pubkeydata);        Fin.close ();    int len = pubkeydata.length;    for (int i=0;i<data.length;i++) {Data[i] = (byte) (Data[i] ^ pubkeydata[i%len]);        } if (args.length = = 4) {FileOutputStream out = new FileOutputStream (args[3]);        Out.write (signbytes);    Out.close (); }  }}


Also compile first:



And look at how to generate the signature file:

Java javasign Private.pem public.bin Test.dat sign.bin


The Test.dat here is the data to be validated, sign.bin the resulting signature file:


Finally, it is how to verify the data using the public key and signature file:

Look at the following code:

Import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.filereader;import Java.io.filewriter;import Java.io.IOException;import Java.io.printstream;import Java.security.keyfactory;import Java.security.keypair;import Java.security.keypairgenerator;import Java.security.publickey;import Java.security.securerandom;import Java.security.security;import Java.security.signature;import Java.security.spec.x509encodedkeyspec;import Javax.xml.bind.datatypeconverter;import Org.bouncycastle.jce.provider.bouncycastleprovider;import Org.bouncycastle.jce.provider.jdkkeypairgenerator;import Org.bouncycastle.openssl.pemreader;import  Org.bouncycastle.openssl.pemwriter;class Verify {public static printstream out = System.out;  public static PrintStream err = System.err;  private static byte[] Pubkeydata = null; public static void Main (string[] args) throws Exception {if (Args.length < 3) {err.println ("Usage:java Verify <public file> <sign file> <data file to verify> ");    System.exit (1);        } File Pubfile = new file (Args[0]);    FileInputStream fin = new FileInputStream (pubfile);    Pubkeydata = new byte[(int) pubfile.length ()];    Fin.read (Pubkeydata);        Fin.close ();  Out.println ("Verifytdata:" +verifydata (New file (Args[1]), new file (Args[2])); public static Boolean Verifydata (File signfile,file datafile) {if (!signfile.exists ()) {return false;} FileInputStream in = null;try {in = new FileInputStream (signfile); byte[] signaturebytes = new byte[(int) signfile.length () ];in.read (signaturebytes); In.close (); in = new FileInputStream (datafile); byte[] data = new byte[(int) datafile.length () ];in.read (data); In.close (); if (!verify (Pubkeydata,signaturebytes,data)) {return false;} return true;} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated Catch Blocke.printstacKtrace ();}  catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {try {in.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}    return false;} public static Boolean verify (Byte[] pubkeybytes,byte[] signaturebytes,byte[] databytes) throws Exception { X509encodedkeyspec Pubkeyspec = new X509encodedkeyspec (pubkeybytes); Keyfactory keyfactory = keyfactory.getinstance ("RSA"); PublicKey PubKey = Keyfactory.generatepublic (PUBKEYSPEC);//load public key Signature sg = signature.getinstance ("SHA1wi    Thrsa ");        Sg.initverify (PubKey);        Sg.update (databytes);    Validate Signature if (Sg.verify (signaturebytes)) {return true;      } return false; }    }


How to use:

Java Verify public.bin Sign.bin Test.dat


In the process of use, the signature file is generally packaged with the data, and in the check to ensure that the public key will not be tampered with, otherwise the checksum is meaningless.


Of course, there is no discussion of the RSA encryption principle, there is a lot of relevant information on the Internet.


The libraries used in this article can be found in the following links:

http://penguindreams.org/blog/signature-verification-between-java-and-python/comment-page-1/#comment-3664169


How to use RSA encryption algorithm to verify data in Android application development

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.