This article summarizes the Android programming encryption algorithm. Share to everyone for your reference, specific as follows:
The BASE64 encryption algorithm of the Android common encryption algorithm:
Package Com.long; /** * Copyright (C) The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "Licen
Se ");
* You could not use this file, except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applic Able or agreed to in writing, software * Distributed under the License was distributed on ' as is ' basis, * without
Warranties or CONDITIONS of any KIND, either express OR implied.
* The License for the specific language governing permissions and * limitations under the License.
* * Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream; * * @author LONG * * */public class Base64 {private static final char[] Legalchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDE
fghijklmnopqrstuvwxyz0123456789+/". 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 >>) &Amp
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);
} 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)) &
lt;< 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;
}
}
}
The AES encryption algorithm for the
Android common encryption algorithm:
Package Com.long;
Import Java.security.SecureRandom;
Import Javax.crypto.Cipher;
Import Javax.crypto.KeyGenerator;
Import Javax.crypto.SecretKey;
Import Javax.crypto.spec.SecretKeySpec; /** * AES Encryption and decryption algorithm * @author long * */public class Encryption {private final static String HEX = "0123456789ABCDE
F "; public static string Encrypt (string seed, String cleartext) throws Exception {byte[] Rawkey = Getrawkey (seed.getbyte
s ());
Byte[] result = Encrypt (Rawkey, cleartext.getbytes ());
return Tohex (Result); public static string decrypt (string seed, string encrypted) throws Exception {byte[] Rawkey = Getrawkey (seed.getb
Ytes ());
byte[] enc = tobyte (encrypted);
Byte[] result = Decrypt (rawkey, ENC);
Return a new String (result);
private static byte[] Getrawkey (byte[] seed) throws Exception {Keygenerator KGen = keygenerator.getinstance ("AES");
securerandom sr = securerandom.getinstance ("sha1prng");
Sr.setseed (seed); Kgen.init (128, SR); 256 bits May is available secretkey Skey = Kgen.generatekey ();
Byte[] raw = skey.getencoded ();
return raw; private static byte[] Encrypt (byte[] raw, byte[] clear) throws Exception {Secretkeyspec Skeyspec = new Secretkeyspec
(Raw, "AES");
Cipher Cipher = cipher.getinstance ("AES");
Cipher.init (Cipher.encrypt_mode, Skeyspec);
Byte[] Encrypted = cipher.dofinal (clear);
return encrypted; private static byte[] Decrypt (byte[] raw, byte[] encrypted) throws Exception {Secretkeyspec Skeyspec = new Secret
Keyspec (Raw, "AES");
Cipher Cipher = cipher.getinstance ("AES");
Cipher.init (Cipher.decrypt_mode, Skeyspec);
byte[] decrypted = cipher.dofinal (encrypted);
return decrypted;
public static string Tohex (String txt) {return Tohex (Txt.getbytes ());
public static string Fromhex (String hex) {return new string (ToByte (hex));
public static byte[] ToByte (String hexstring) {int len = Hexstring.length ()/2;
Byte[] result = new Byte[len]; for (int i = 0; i < Len;
i++) Result[i] = integer.valueof (hexstring.substring (2 * I, 2 * i + 2), Bytevalue ();
return result;
public static String Tohex (byte[] buf) {if (buf = = null) return "";
StringBuffer result = new StringBuffer (2 * buf.length);
for (int i = 0; i < buf.length. i++) {Appendhex (result, buf[i));
return result.tostring (); private static void Appendhex (StringBuffer sb, byte b) {Sb.append (Hex.charat ((b >> 4) & 0x0f)). Append (HEX.
CharAt (b & 0x0f));
}
}
The RAS encryption algorithm for the Android common encryption algorithm:
Import Java.security.Key;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.interfaces.RSAPrivateKey;
Import Java.security.interfaces.RSAPublicKey;
Import Java.security.spec.PKCS8EncodedKeySpec;
Import Java.security.spec.X509EncodedKeySpec;
Import Javax.crypto.Cipher;
Import Sun.misc.BASE64Decoder;
Import Sun.misc.BASE64Encoder;
public class Rsahelper {public static PublicKey Getpublickey (String key) throws Exception {byte[] keybytes;
Keybytes = (new Base64decoder ()). Decodebuffer (key);
X509encodedkeyspec Keyspec = new X509encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance ("RSA");
PublicKey PublicKey = Keyfactory.generatepublic (Keyspec);
return publickey;
public static Privatekey Getprivatekey (String key) throws Exception {byte[] keybytes; Keybytes = (new Base64decoder ()). Decodebuffer (key);
Pkcs8encodedkeyspec Keyspec = new Pkcs8encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance ("RSA");
Privatekey Privatekey = keyfactory.generateprivate (Keyspec);
return privatekey;
public static String getkeystring (key key) throws Exception {byte[] keybytes = key.getencoded ();
String s = (new Base64encoder ()). Encode (keybytes);
return s; public static void Main (string[] args) throws Exception {Keypairgenerator Keypairgen = Keypairgenerator.getinsta
NCE ("RSA");
Number of key digits keypairgen.initialize (1024);
Key pair KeyPair KeyPair = Keypairgen.generatekeypair ();
Public key PublicKey PublicKey = (rsapublickey) keypair.getpublic ();
Private key Privatekey Privatekey = (rsaprivatekey) keypair.getprivate ();
String publickeystring = getkeystring (PublicKey);
System.out.println ("public:\n" + publickeystring);
String privatekeystring = getkeystring (Privatekey); System.out.println ("Private:\n "+ privatekeystring);
Encryption and decryption class Cipher Cipher = Cipher.getinstance ("RSA");//cipher.getinstance ("rsa/ecb/pkcs1padding"); Clear byte[] PlainText = "We are all very well!"
Mail: @sina. com ". GetBytes ();
Encryption Cipher.init (Cipher.encrypt_mode, PublicKey);
byte[] Enbytes = cipher.dofinal (plaintext);
The key PublicKey = Getpublickey (publickeystring) is obtained by the key string;
Privatekey = Getprivatekey (privatekeystring);
Decrypt Cipher.init (Cipher.decrypt_mode, Privatekey);
Byte[]debytes = Cipher.dofinal (enbytes);
publickeystring = getkeystring (PublicKey);
System.out.println ("public:\n" +publickeystring);
privatekeystring = getkeystring (Privatekey);
System.out.println ("private:\n" + privatekeystring);
string s = new string (debytes);
System.out.println (s);
}
}
I hope this article will help you with your Android programming.