[022] A consistent encryption tool for Android, iphone and Java three platforms __android

Source: Internet
Author: User
Tags base64 decrypt reserved stringbuffer

Having previously been an Android, and recently developing an iphone client, the most troubling of all is the inconsistency between the Java, Android and iphone three platforms plus decryption . Because the end of the phone is usually the Java-developed web service,android and iphone clients invoke the same Web Service interface, for data security considerations, to encrypt the data. The headaches are coming, it's hard to write a set of encryption programs, and the results are consistent between 3 platforms, and it's not always possible to write a Web service interface for Android and iphone two clients. I'm sure there will be a lot of friends out there, sharing a set of 3DES encryption programs that will allow Java, Android and iphone three platforms to be decrypted .

The first is the Java side of the encryption tool class, it also applies to the Android side, without any modification, you can ensure that Java and the Android side of the encryption and decryption consistent, and Chinese will not garbled.

Package org.liuyq.des3;

Import Java.security.Key;
Import Javax.crypto.Cipher;
Import Javax.crypto.SecretKeyFactory;
Import Javax.crypto.spec.DESedeKeySpec;

Import Javax.crypto.spec.IvParameterSpec; /** * 3DES Encryption Tool class * * @author Liufeng * @date 2012-10-11/public class Des3 {//Key private final static String s
	Ecretkey = "liuyunqiang@lx100$ #365 #$";
	Vector private final static String IV = "01234567";

	Encryption and decryption unified use of the encoding method private final static String encoding = "Utf-8"; /** * 3DES Encryption * * @param plaintext Plain text * @return * @throws Exception/public static string encode (String
		PlainText) throws Exception {Key deskey = null;
		Desedekeyspec spec = new Desedekeyspec (Secretkey.getbytes ());
		Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");

		Deskey = Keyfactory.generatesecret (spec);
		Cipher Cipher = cipher.getinstance ("desede/cbc/pkcs5padding");
		Ivparameterspec ips = new Ivparameterspec (Iv.getbytes ()); Cipher.init (Cipher.encrypt_mode, desKey, IPs);
		byte[] EncryptData = cipher.dofinal (plaintext.getbytes (encoding));
	Return Base64.encode (encryptdata); /** * 3DES Decryption * * @param encrypttext Encrypted text * @return * @throws Exception/public static String decode (St
		Ring Encrypttext) throws Exception {Key deskey = null;
		Desedekeyspec spec = new Desedekeyspec (Secretkey.getbytes ());
		Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");
		Deskey = Keyfactory.generatesecret (spec);
		Cipher Cipher = cipher.getinstance ("desede/cbc/pkcs5padding");
		Ivparameterspec ips = new Ivparameterspec (Iv.getbytes ());

		Cipher.init (Cipher.decrypt_mode, Deskey, IPs);

		byte[] Decryptdata = cipher.dofinal (Base64.decode (Encrypttext));
	return new String (Decryptdata, encoding);
 }
}

The

        encryption tool class above uses the Base64 class, which has the following source code:

Package org.liuyq.des3;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;

Import Java.io.OutputStream; /** * BASE64 Coding Tool Class * * @author Liufeng * @date 2012-10-11/public class Base64 {private static final char[] Lega

	Lchars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/". ToCharArray ();
		public static String encode (byte[] Data {int start = 0;
		int len = data.length;

		StringBuffer buf = new StringBuffer (data.length * 3/2);
		int end = Len-3;
		int i = start;

		int n = 0; while (I <= end) {int d = (((((int) data[i]) & 0x0ff) << 16 | ((((((int) Data[i + 1]) & 0X0FF) << 8) |

			(((int) Data[i + 2]) & 0X0FF);
			Buf.append (legalchars[(d >> a) & 63]);
			Buf.append (legalchars[(d >>) & 63]);
			Buf.append (legalchars[(d >> 6) & 63]);

			Buf.append (Legalchars[d & 63]);

			i + 3;
				if (n++ >=) {n = 0;
			Buf.append (""); } if (i = = start + len-2{int d = (((((int) data[i]) & 0x0ff) << 16 |

			((((int) Data[i + 1]) & 255) << 8);
			Buf.append (legalchars[(d >> a) & 63]);
			Buf.append (legalchars[(d >>) & 63]);
			Buf.append (legalchars[(d >> 6) & 63]);
		Buf.append ("=");

			else if (i = = start + len-1) {int d = ((int) data[i]) & 0X0FF) << 16;
			Buf.append (legalchars[(d >> a) & 63]);
			Buf.append (legalchars[(d >>) & 63]);
		Buf.append ("= =");
	return buf.tostring ();
		private static int decode (char c) {if (c >= ' A ' && C <= ' Z ') return ((int) c)-65;
		else if (c >= ' a ' && c <= ' z ') return ((int) c)-97 + 26;
		else if (c >= ' 0 ' && C <= ' 9 ') return ((int) c)-48 + 26 + 26;
			else switch (c) {case ' + ': return 62;
			Case '/': return 63;
			Case ' = ': return 0;
			Default:throw new RuntimeException ("Unexpected code:" + C); }/** * DeCodes the given BASE64 encoded String to a new byte array.
	 The byte array holding the decoded data is returned.
		*/public static byte[] Decode (String s) {bytearrayoutputstream bos = new Bytearrayoutputstream ();
		try {decode (s, BOS);
		catch (IOException e) {throw new RuntimeException ();
		} byte[] Decodedbytes = Bos.tobytearray ();
			try {bos.close ();
		BOS = NULL;
		The catch (IOException ex) {System.err.println ("Error while decoding BASE64:" + ex.tostring ());
	return decodedbytes;

		} private static void Decode (String s, OutputStream os) throws IOException {int i = 0;

		int len = S.length ();

			while (true) {while (I < Len && S.charat (i) <= ') i++;

			if (i = = len) break;  int tri = (decode (S.charat (i)) <<) + (decode (S.charat (i + 1)) << (Decode (S.charat (i + 2)) << 6)

			+ (Decode (S.charat (i + 3)));
			Os.write ((Tri >>) & 255);
			if (S.charat (i + 2) = = ' = ') break; Os.wriTe ((Tri >> 8) & 255);
			if (S.charat (i + 3) = = ' = ') break;

			Os.write (Tri & 255);
		i + 4;
 }
	}
}

Next is the iphone side of the encryption program, of course, with OJBECTIVE-C write 3DES encryption program, the source code is as follows:

//  DES3Util.h
//  LX100-GZ////
Created by Liu Feng on  12-10-10.  Copyright http://blog.csdn.net/lyq8479. All rights reserved.

#import <Foundation/Foundation.h>


@interface des3util:nsobject {

}

//encryption method
+ ( nsstring*) Encrypt: (nsstring*) plaintext;

Decryption method
+ (nsstring*) Decrypt: (nsstring*) Encrypttext;

@end
DES3UTIL.M//LX100-GZ////Created by Liu Feng on 12-9-17. Copyright http://blog.csdn.net/lyq8479.
All rights reserved. #import "DES3Util.h" #import <CommonCrypto/CommonCryptor.h> #import "GTMBase64.h" #define Gkey @ "liuyunqiang@ lx100$ #365 #$ "#define GIV @ 01234567" @implementation des3util//encryption Method + (nsstring*) Encrypt: (nsstring*) plain
	Text {nsdata* data = [plaintext datausingencoding:nsutf8stringencoding];
	size_t plaintextbuffersize = [data length];
    
    const void *vplaintext = (const void *) [data bytes];
    Cccryptorstatus Ccstatus;
    uint8_t *bufferptr = NULL;
    size_t bufferptrsize = 0;
    
    size_t movedbytes = 0;
    Bufferptrsize = (plaintextbuffersize + kccblocksize3des) & ~ (KCCBLOCKSIZE3DES-1);
    Bufferptr = malloc (bufferptrsize * sizeof (uint8_t));
    
    memset (void *) Bufferptr, 0x0, bufferptrsize);
    const void *vkey = (const void *) [Gkey utf8string]; const void *vinitvec = (const void *) [GIv utf8stRing];
                       Ccstatus = Cccrypt (Kccencrypt, Kccalgorithm3des, kccoptionpkcs7padding, Vkey, Kcckeysize3des, Vinitvec, VP Laintext, Plaintextbuffersize, (void *) Bufferptr, buf
    
    Ferptrsize, &movedbytes);
	NSData *mydata = [NSData datawithbytes: (const void *) Bufferptr length: (Nsuinteger) movedbytes];
    NSString *result = [GTMBase64 stringbyencodingdata:mydata];
return result; }//Decryption method + (nsstring*) Decrypt: (nsstring*) encrypttext {nsdata *encryptdata = [GTMBase64 decodedata:[encrypttext data
	Usingencoding:nsutf8stringencoding]];
	size_t plaintextbuffersize = [encryptdata length];
    
    const void *vplaintext = [encryptdata bytes];
    Cccryptorstatus Ccstatus;
    uint8_t *bufferptr = NULL;
    size_t bufferptrsize = 0; size_t movedbytes = 0;
    
    Bufferptrsize = (plaintextbuffersize + kccblocksize3des) & ~ (KCCBLOCKSIZE3DES-1);
    Bufferptr = malloc (bufferptrsize * sizeof (uint8_t));
    
    memset (void *) Bufferptr, 0x0, bufferptrsize);
    const void *vkey = (const void *) [Gkey utf8string];
    
    const void *vinitvec = (const void *) [gIv utf8string];
                       Ccstatus = Cccrypt (Kccdecrypt, Kccalgorithm3des, kccoptionpkcs7padding, Vkey, Kcckeysize3des, Vinitvec, VP Laintext, Plaintextbuffersize, (void *) Bufferptr, buf
    
    Ferptrsize, &movedbytes); NSString *result = [[[NSString Alloc] initwithdata:[nsdata datawithbytes: (const void *) Bufferptr length: (Nsuinteg
    ER) movedbytes] encoding:nsutf8stringencoding] autorelease];
return result; } @end

The iphone end of the encryption tool class introduced the "GTMBase64.h", this is the iOS platform Base64 coding tool class, is not posted here the relevant code, the need for Baidu to find, really can not find the reply to me message.

OK, let's try it, java,android and the iphone three platform encryption inconsistency problem is not solved. In fact, there is a better way to achieve this, that is, the C language to write a set of encryption programs, so that in the iOS platform can be directly using the C program, and in Java and Android end through JNI to invoke the encryption method written in C language, This is not the implementation of the 3 platform invoke the same set of encryption program it.


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.