Two encryption algorithms required for Android Network Transmission: MD5 and RSA (with java to complete the test code)

Source: Internet
Author: User
Tags md5 digest modulus

MD5 and RSA are the two most commonly used algorithms in network transmission. After understanding the principles of these two algorithms, you can get a general idea of what encryption is like. However, these two algorithms use different environments and are just complementary.

I. MD5 Algorithm

First, MD5 is irreversible and can only be encrypted but cannot be decrypted. For example, if the plaintext value is yanzi1225627 and the MD5 encrypted string is 14F2AE15259E2C276A095E7394DA0CA9, but yanzi1225627is not listed in the next large string. Therefore, it can be used to store user input passwords on servers. Now download file verification file has been tampered with is also used in the middle of it, the principle of SEE: http://blog.csdn.net/forgotaboutgirl/article/details/7258109 whether on Android or pc with java to achieve MD5 are relatively easy, because java has already implemented java. security. in MessageDigest. Below 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 (); // The MessageDigest object that obtains the MD5 Digest algorithm. MessageDigest mdInst = MessageDigest. getInstance ("MD5"); // use the specified byte to update the abstract mdInst. update (btInput); // obtain the ciphertext byte [] md = mdInst. digest (); // converts the ciphertext to a hexadecimal string in the form of 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 & 0xf]; str [k ++] = hexDigits [byte0 & 0xf];} return new String (str);} catch (Exception e) {e. printStackTrace (); return null ;}}}

Use the following two lines of code:

/************************************ MD5 encryption Test *****************************/
String srcString = "yanzi1225627 ";
System. out. println ("MD5 encrypted =" + MD5Util. getMD5String (srcString ));

Ii. RSA Encryption

RSA is reversible. A string can be encrypted by rsa and uploaded to the peer end, such as the server, for decryption. The premise is that the server knows the decrypted private key. Of course, it is best not to transmit the key over the network. The following variables are required in the RSA Algorithm Description:

1. p and q are not equal. They are two prime numbers that are large enough. P and q are confidential.

2. n = p * q n is public.

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

4. e is the prime number of mutual quality with f (n ).

5. Calculated parameter d

6. After five steps above, the public key KU = (e, n) Private Key KR = (d, n) is obtained)

The following two articles clearly describe this:

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

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

The following is the java RSAUtil. java class:

Package org. rsa. util; import javax. crypto. cipher; import java. security. *; import java. security. spec. RSAPublicKeySpec; import java. security. spec. rsw.vatekeyspec; import java. security. spec. invalidKeySpecException; import java. security. interfaces. rsw.vatekey; import java. security. interfaces. RSAPublicKey; import java. io. *; import java. math. bigInteger;/*** RSA tool class. Provides encryption, decryption, and key-to-Peer generation methods. * The http://www.bouncycastle.org needs to be downloaded from the bcprov-jdk14-123.jar. * RSA encryption principle overview * RSA Security depends on the decomposition of large numbers. Both the public key and private key are functions with two large prime numbers (more than 100 decimal digits. * According to speculation, it is difficult to deduce the plain text from a key and ciphertext. It is equivalent to decomposing the product * ==================== of two prime numbers. ========================================================== ======= * (the security of the algorithm has not been proved theoretically) * ===================================================== ===================================* key generation: * 1. select two large prime numbers p, q, and calculate n = p * q; * 2. random selection of encryption key e, requires e and P-1) * (q-1) mutual quality * 3. use the Euclid algorithm to calculate and decrypt the key d, so that it meets e * d = 1 (mod (p-1) * (q-1) (where n, d also need to be mutually qualitative) * 4: so far, the Public Key is (n, e) and the private key is (n, d) * ===================================================== =========================================== * encryption and decryption method: * 1. first, the information to be encrypted m (binary representation) is divided into long data blocks m1, m2 ,..., mi block length s (as big as possible), 2 ^ s
 
  
* @ Author Dong Liwei
  
* Version:
* Description:
* Creation Time: 09:58:16
* File description:
* Modifier:
* Modification date:
* Description:
*/Public class RSAUtil {// key pair private KeyPair keyPair = null;/*** initialize the key pair */public RSAUtil () {try {this. keyPair = this. generateKeyPair ();} catch (Exception e) {e. printStackTrace () ;}/ *** generate key pair * @ return KeyPair * @ throws Exception */private KeyPair generateKeyPair () throws Exception {try {KeyPairGenerator keyPairGen = KeyPairGenerator. getInstance ("RSA", new org. bouncycastle. jce. provider. bouncyCastleProvi Der (); // This value is related to the block encryption size. It can be changed, but not too large. Otherwise, the efficiency will be lower than 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 generateRSAPublicKey (byte [] modulus, byte [] publicEx Ponent) throws Exception {KeyFactory keyFac = null; try {keyFac = KeyFactory. getInstance ("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 rs?vatekey * @ throws Exception */private rs?vatekey pair (byte [] modulus, byte [] privateExponent) throws Exception {KeyFactory keyFac = null; try {keyFac = KeyFactory. getInstance ("RSA", new org. bouncycastle. jce. provider. bouncyCastleProvider ());} Catch (NoSuchAlgorithmException ex) {throw new Exception (ex. getMessage ();} RSAPrivateKeySpec priKeySpec = new rs?vatekeyspec (new BigInteger (modulus), new BigInteger (privateExponent); try {return (rs?vatekey) keyFac. generatePrivate (priKeySpec);} catch (InvalidKeySpecException ex) {throw new Exception (ex. getMessage () ;}}/*** encrypted ** @ param key the Encrypted key * @ param data the plaintext data to be encrypted * @ return encrypted data * @ throws E Xception */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 the size of the encrypted block. For example, the size of the encrypted block is 128 bytes, the size of the encrypted block is 1024 bytes, and the size of the encrypted block is 127 bytes; // Therefore, there are two encrypted blocks. The first 127 byte and the second is 1 byteint blockSize = cipher. getBlockSize (); int outputSize = cipher. getOutputSize (data. l Ength); // The block size after the encrypted block is obtained. 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 * blockSize> blockSize) cipher. doFinal (data, I * blockSize, blockSize, raw, I * outputSize); elsecipher. doFinal (data, I * blockSize, data. length-I * blockSize, raw, I * outputSize); // The doUpdate method is unavailable. Check the source code and find that there is no actual operation after each doUpdate. In addition to putting byte [] into ByteArrayOutputStream //, the last doFinal operation encrypts all byte, however, the size of the encrypted block may exceed the OutputSize, so we have to use the dofinal method. I ++;} return raw;} catch (Exception e) {throw new Exception (e. getMessage ());}} /*** decrypt * @ param key the decrypted Key * @ param raw the encrypted data * @ return the decrypted plaintext * @ throws Exception */public byte [] decrypt (key key, byte [] raw) 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 (64); 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 pubKey = (RSAPublicKey) keyPair. getPublic (); // obtain the Public Key coefficient (in byte array form) byte [] pubModBytes = pubKey. getModulus (). toByteArray (); // return public key public index (in byte array form) byte [] pubPubExpBytes = pubKey. getPublicExponent (). toByteArray (); // generate the Public Key RSAPublicKey recoveryPubKey = this. generateRSAPublicKey (pubModBytes, pubPubExpBytes); return recoveryPubKey;}/*** get private key * @ return * @ throws Exception */public rsw.vatekey getrsw.vatekey () throws Exception {// obtain the private key rs?vatekey priKey = (rs?vatekey) keyPair. getPrivate (); // return the private key coefficient (in byte array form) byte [] priModBytes = priKey. getModulus (). toByteArray (); // returns the private key private index (in byte array form) byte [] priPriExpBytes = priKey. getPrivateExponent (). toByteArray (); // generate the private key rsw.vatekey 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 ();
Rsw.vatekey priKey = rsa. getrsw.vatekey ();
Byte [] enRsaBytes = rsa. encrypt (pubKey, str. getBytes ());
String enRsaStr = new String (enRsaBytes, "UTF-8 ");
System. out. println ("encrypted =" + enRsaStr );
System. out. println ("decrypted =" + new String (rsa. decrypt (priKey, rsa. encrypt (pubKey, str. getBytes ()))));
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

The execution result is as follows:

After encryption = s? Ko? 1 @ lo ???? BJ? IE ??? 1Ux? Kx &?? = ?? N
O ?? L?> ????? 2r? Y ?? 8 v-\ ?? '???? R? T3? -3y? HjL? M ?? Se? Z ???????~? "?? E ?? XZ? Why?
Decrypted = yanzi1225627

The above Code requires an rsa. jar package. The download link and the above test code are packaged. For the download link, see:

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




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.