Two encryption algorithms required for Android network transmission: MD5 and RSA (with Java Complete test code)

Source: Internet
Author: User
Tags getmessage md5 digest md5 encryption modulus

MD5 and RSA are the most commonly used two algorithms in network transmission, knowing the principle of these two algorithms can roughly know what the encryption is all about. But the two algorithms use different environments, just complementary.

First, MD5 algorithm

First of all, MD5 is irreversible and can only be encrypted and not decrypted. For example, the plaintext is yanzi1225627, get MD5 encrypted string is: 14F2AE15259E2C276A095E7394DA0CA9 but not by the back of a large series of inverted yanzi1225627. Therefore, you can use it to store user-entered passwords on the server. It is also used to download a file to verify whether the file is tampered with in the middle, see the principle: http://blog.csdn.net/forgotaboutgirl/article/details/7258109 It's easier to implement MD5 in Java on Android or on a PC, because Java has done it in java.security.MessageDigest. Here is a Md5util.java class:

Package Org.md5.util;import Java.security.messagedigest;public class Md5util {public final static String getmd5string (  String s) {char hexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};try {byte[] Btinput = S.getbytes ();//Get MD5 Digest algorithm MessageDigest object MessageDigest mdinst = messagedigest.getinstance ("MD5");// Updates the digest using the specified byte mdinst.update (btinput);//Get ciphertext byte[] MD = Mdinst.digest ();//convert ciphertext into a 16-binary string form int j = Md.length;char str[] = New Char[j * 2];int k = 0;for (int i = 0; i < J; i++) {byte byte0 = md[i];str[k++] = hexdigits[byte0 >>> 4 &am P 0xf];str[k++] = hexdigits[byte0 & 0xf];} return new String (str); catch (Exception e) {e.printstacktrace (); return null;}}}

Called by the following two lines of code:

/************************************MD5 Encryption Test *****************************/
String srcstring = "yanzi1225627";
System.out.println ("MD5 After encryption =" + md5util.getmd5string (srcstring));

Second, RSA encryption

RSA is reversible, a string can be encrypted by RSA, after the encrypted string to the peer, such as the server, and then decrypt. The premise is that the server knows the decrypted private key, of course, this private key is best not to network transmission. The following variables are required in the RSA algorithm description:

1, p and q are unequal, large enough of two prime numbers. P and Q are confidential.

2, n = p*q n is public

3, f (n) = (p-1) * (q-1)

4, E is and f (n) coprime prime number

5. Calculation parameter D

6. The public key ku= (e,n) private key kr= (D,n) is computed by the above 5 steps.

The following two articles have a clear description of this:

Http://wenku.baidu.com/view/e53fbe36a32d7375a417801b.html

Http://bank.hexun.com/2009-06-24/118958531.html

Here is the Java implementation Rsautil.java class:

Package Org.rsa.util;import Javax.crypto.cipher;import Java.security.*;import java.security.spec.RSAPublicKeySpec; Import Java.security.spec.rsaprivatekeyspec;import Java.security.spec.invalidkeyspecexception;import Java.security.interfaces.rsaprivatekey;import Java.security.interfaces.rsapublickey;import Java.io.*;import java.math.biginteger;/** * RSA Tool class. Provides encryption, decryption, and generation of key equivalence methods. * Need to download Bcprov-jdk14-123.jar to http://www.bouncycastle.org.   * Overview of RSA Encryption principle * RSA security relies on the decomposition of large numbers, both public and private keys are functions of two large primes (more than 100 decimal bits). * It is assumed that the difficulty of inferring clear text from a key and cipher is equivalent to decomposing the product of two large primes * =================================================================== *  (The security of the algorithm is not proven by theory) * =================================================================== * key generation: * 1. Select two large prime p,q, calculate   N=p*q;  * 2. Randomly select the encryption key E, which requires E and (p-1) * (q-1) coprime * 3. Use the Euclid algorithm to calculate the decryption key D so that it satisfies e*d = 1 (mod (p-1) * (q-1)) (where n,d also coprime) * 4: The public key is thus (n,e) The private key is (n,d) * =================================================================== * Plus decryption method: * 1. The first information to be encrypted m (binary tabulation Equal length data block m1,m2,..., mi block length s (as large as possible), where 2^s<n * 2: The corresponding ciphertext is: CI = mi^e (mod n) * 3: The decryption is calculated as follows: mi = ci^d (mod n) * =======================   ============================================ * RSA Speed * Due to the large number of calculations, RSA fastest case is also 100 times times slower than DES, whether it is software or hardware implementation. * Speed has been a drawback of RSA.  Generally, only a small amount of data encryption is used. * File name:rsautil.java<br> * @author Dongliwei <br> * Version:<br> * Description:<br> * creation time: 2008-9-23 pm 09:58:16&LT;BR > * File Description:<br> * Modified by:<br> * Modified Date:<br> * Modified description:<br> */public class Rsautil {//Key pair Private KeyPair KeyPair = null;/** * Initialize key pair */public Rsautil () {try {This.keypair = This.generatekeypair ();} catch (Exception e) {e.printst Acktrace ();}}  /*** generate key Pair * @return keypair* @throws exception*/private KeyPair Generatekeypair () throws Exception {try {keypairgenerator Keypairgen = Keypairgenerator.getinstance ("RSA", New Org.bouncycastle.jce.provider.BouncyCastleProvider ());// This value is related to the size of the block encryption, can be changed, but not too large, otherwise the efficiency will be low final int key_size = 1024;keypairgen.initialize (key_size, New SecureRandom ()); KeyPair KeyPair = Keypairgen.genkeYpair (); return keyPair;} catch (Exception e) {throw new Exception (E.getmessage ());}} /*** generate Public key * @param modulus* @param publicexponent* @return rsapublickey* @throws exception*/private rsapublickey generater Sapublickey (byte[] modulus, byte[] publicexponent) throws Exception {Keyfactory Keyfac = null;try {KEYFAC = Keyfactory.get Instance ("RSA", New Org.bouncycastle.jce.provider.BouncyCastleProvider ());} catch (NoSuchAlgorithmException ex) {throw new Exception (Ex.getmessage ());} Rsapublickeyspec Pubkeyspec = new Rsapublickeyspec (new BigInteger (modulus), new BigInteger (publicexponent)); try { Return (Rsapublickey) keyfac.generatepublic (PUBKEYSPEC);} catch (Invalidkeyspecexception ex) {throw new Exception (Ex.getmessage ());}} /*** Generate private key * @param modulus* @param privateexponent* @return rsaprivatekey* @throws exception*/private rsaprivatekey genera Tersaprivatekey (byte[] modulus, byte[] privateexponent) throws Exception {Keyfactory Keyfac = null;try {KEYFAC = KeyFactor Y.getinstance ("RSA", New Org.bounCycastle.jce.provider.BouncyCastleProvider ());} catch (NoSuchAlgorithmException ex) {throw new Exception (Ex.getmessage ());} Rsaprivatekeyspec Prikeyspec = new Rsaprivatekeyspec (new BigInteger (modulus), new BigInteger (privateexponent)); try { Return (Rsaprivatekey) keyfac.generateprivate (PRIKEYSPEC);} catch (Invalidkeyspecexception ex) {throw new Exception (Ex.getmessage ());}} /*** encryption * @param key Encryption Key * @param data to be encrypted plaintext data * @return Encrypted data * @throws Exception*/public byte[] Encrypt (key key, byte[] Data) throws Exception {try {Cipher Cipher = cipher.getinstance ("RSA", new Org.bouncycastle.jce.provider.BouncyCastleProvider ()); Cipher.init (Cipher.encrypt_mode, key);//Obtain an encrypted block size, such as: Before the encryption data is 128 byte, and the KEY_SIZE=1024 encryption block size is 127 byte, after encryption is 128 byte;//so there are 2 encryption blocks, the first 127 byte the second is 1 byteint blockSize = Cipher.getblocksize (); int outputsize = Cipher.getoutputsize (data.length);//Get encrypted block encrypted after block size int leavedsize = data.length% Blocksize;int blockssize = leavedsize! = 0? Data.length/blocksize + 1:data.length/blocksize;byTe[] Raw = new Byte[outputsize * Blockssize];int i = 0;while (data.length-i * blockSize > 0) {if (Data.length-i * b Locksize > BlockSize) cipher.dofinal (data, I * blockSize, blockSize, Raw, I * outputsize); elsecipher.dofinal (data, I * b Locksize, Data.length-i * blockSize, RAW, I * outputsize);//This doupdate method is not available, after viewing the source code found after each doupdate and there is no actual action except byte[] Put in the Bytearrayoutputstream//, and the last dofinal when all the byte[] to encrypt, but at this time the size of the encryption block is likely to have exceeded the outputsize so have to use the Dofinal method. i++;} return raw;} catch (Exception e) {throw new Exception (E.getmessage ());}} /*** Decrypt * Key decrypted by @param key * @param raw encrypted data * @return decrypted plaintext * @throws exception*/public byte[] Decrypt (key key, byte[] Ra W) throws Exception {try {Cipher Cipher = cipher.getinstance ("RSA", new Org.bouncycastle.jce.provider.BouncyCastleProvider ()); Cipher.init (cipher. Decrypt_mode, key); int blockSize = Cipher.getblocksize (); Bytearrayoutputstream bout = new Bytearrayoutputstream (+), int j = 0;while (raw.length-j * blockSize > 0) {bout.write (Cipher.dofinal (RAw, J * BlockSize, BlockSize)); J + +;} return Bout.tobytearray ();} catch (Exception e) {throw new Exception (E.getmessage ());}} /** * Return Public key * @return * @throws Exception */public rsapublickey Getrsapublickey () throws exception{//get public key Rsapublickey PUBK EY = (Rsapublickey) keypair.getpublic ();//Get Public key coefficients (in byte array form) byte[] pubmodbytes = Pubkey.getmodulus (). Tobytearray ();// Returns the public key common exponent (in byte array form) byte[] pubpubexpbytes = Pubkey.getpublicexponent (). Tobytearray ();//Generate Public key Rsapublickey Recoverypubkey = This.generatersapublickey (pubmodbytes,pubpubexpbytes); return recoverypubkey;} /** * Get Private key * @return * @throws Exception */public rsaprivatekey Getrsaprivatekey () throws exception{//get private key Rsaprivatekey p Rikey = (Rsaprivatekey) keypair.getprivate ();//returns the private key coefficient (in byte array form) byte[] primodbytes = Prikey.getmodulus (). Tobytearray () ;//Returns private key index (byte array form) byte[] pripriexpbytes = Prikey.getprivateexponent (). Tobytearray ();//Generate Private key Rsaprivatekey Recoveryprikey = This.generatersaprivatekey (primodbytes,pripriexpbytes); return recoveryprikey;}}
Test Code:

/****************************rsa encryption and decryption test ********************************/
try {
Rsautil RSA = new Rsautil ();
String str = "yanzi1225627";
Rsapublickey PubKey = Rsa.getrsapublickey ();
Rsaprivatekey Prikey = Rsa.getrsaprivatekey ();
byte[] enrsabytes = Rsa.encrypt (Pubkey,str.getbytes ());
String enrsastr = new String (enrsabytes, "UTF-8");
SYSTEM.OUT.PRINTLN ("after encryption = =" + enrsastr);
System.out.println ("after decryption = =" + New String (Rsa.decrypt (Prikey, Rsa.encrypt (Pubkey,str.getbytes ())));
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Here is the result of the execution:

==s?ko?1@lo???? after encryption Bj?ie??? 1Ux? Kx&?? =?? N
O? ?l?>????? 2r?y?? 8v-\a?? `???? R?t3?-3y?hjl? M?? Se? Z??????? ~?"?? E?? XZ? Clover?
==yanzi1225627 after decryption

The above code needs to use a package Rsa.jar, download link and the test code above I have packaged, download the link under the interview:

http://download.csdn.net/detail/yanzi1225627/7382263




Related Article

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.