Android加密算法:AES、Base64加密算法

摘自: http://blog.csdn.net/yuxlong2010/article/details/7892146

 

android常用加密算法之Base64加密算法:

 

  1. package com.long;  
  2.   
  3. /** 
  4.  * Copyright (C) 2010 The Android Open Source Project 
  5.  * 
  6.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  7.  * you may not use this file except in compliance with the License. 
  8.  * You may obtain a copy of the License at 
  9.  * 
  10.  *      http://www.apache.org/licenses/LICENSE-2.0 
  11.  * 
  12.  * Unless required by applicable law or agreed to in writing, software 
  13.  * distributed under the License is distributed on an "AS IS" BASIS, 
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  15.  * See the License for the specific language governing permissions and 
  16.  * limitations under the License. 
  17.  */  
  18.   
  19. import java.io.ByteArrayOutputStream;  
  20. import java.io.IOException;  
  21. import java.io.OutputStream;  
  22.   
  23. /* 
  24.  * @author long 
  25.  * 
  26.  */  
  27. public class Base64 {  
  28.     private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"  
  29.             .toCharArray();  
  30.   
  31.     public static String encode(byte[] data) {  
  32.         int start = 0;  
  33.         int len = data.length;  
  34.         StringBuffer buf = new StringBuffer(data.length * 3 / 2);  
  35.   
  36.         int end = len - 3;  
  37.         int i = start;  
  38.         int n = 0;  
  39.   
  40.         while (i <= end) {  
  41.             int d = ((((int) data[i]) & 0x0ff) << 16)  
  42.                     | ((((int) data[i + 1]) & 0x0ff) << 8)  
  43.                     | (((int) data[i + 2]) & 0x0ff);  
  44.   
  45.             buf.append(legalChars[(d >> 18) & 63]);  
  46.             buf.append(legalChars[(d >> 12) & 63]);  
  47.             buf.append(legalChars[(d >> 6) & 63]);  
  48.             buf.append(legalChars[d & 63]);  
  49.   
  50.             i += 3;  
  51.   
  52.             if (n++ >= 14) {  
  53.                 n = 0;  
  54.                 buf.append(" ");  
  55.             }  
  56.         }  
  57.   
  58.         if (i == start + len - 2) {  
  59.             int d = ((((int) data[i]) & 0x0ff) << 16)  
  60.                     | ((((int) data[i + 1]) & 255) << 8);  
  61.   
  62.             buf.append(legalChars[(d >> 18) & 63]);  
  63.             buf.append(legalChars[(d >> 12) & 63]);  
  64.             buf.append(legalChars[(d >> 6) & 63]);  
  65.             buf.append("=");  
  66.         } else if (i == start + len - 1) {  
  67.             int d = (((int) data[i]) & 0x0ff) << 16;  
  68.   
  69.             buf.append(legalChars[(d >> 18) & 63]);  
  70.             buf.append(legalChars[(d >> 12) & 63]);  
  71.             buf.append("==");  
  72.         }  
  73.   
  74.         return buf.toString();  
  75.     }  
  76.   
  77.     private static int decode(char c) {  
  78.         if (c >= 'A' && c <= 'Z')  
  79.             return ((int) c) - 65;  
  80.         else if (c >= 'a' && c <= 'z')  
  81.             return ((int) c) - 97 + 26;  
  82.         else if (c >= '0' && c <= '9')  
  83.             return ((int) c) - 48 + 26 + 26;  
  84.         else  
  85.             switch (c) {  
  86.             case '+':  
  87.                 return 62;  
  88.             case '/':  
  89.                 return 63;  
  90.             case '=':  
  91.                 return 0;  
  92.             default:  
  93.                 throw new RuntimeException("unexpected code: " + c);  
  94.             }  
  95.     }  
  96.   
  97.     public static byte[] decode(String s) {  
  98.   
  99.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  100.         try {  
  101.             decode(s, bos);  
  102.         } catch (IOException e) {  
  103.             throw new RuntimeException();  
  104.         }  
  105.         byte[] decodedBytes = bos.toByteArray();  
  106.         try {  
  107.             bos.close();  
  108.             bos = null;  
  109.         } catch (IOException ex) {  
  110.             System.err.println("Error while decoding BASE64: " + ex.toString());  
  111.         }  
  112.         return decodedBytes;  
  113.     }  
  114.   
  115.     private static void decode(String s, OutputStream os) throws IOException {  
  116.         int i = 0;  
  117.   
  118.         int len = s.length();  
  119.   
  120.         while (true) {  
  121.             while (i < len && s.charAt(i) <= ' ')  
  122.                 i++;  
  123.   
  124.             if (i == len)  
  125.                 break;  
  126.   
  127.             int tri = (decode(s.charAt(i)) << 18)  
  128.                     + (decode(s.charAt(i + 1)) << 12)  
  129.                     + (decode(s.charAt(i + 2)) << 6)  
  130.                     + (decode(s.charAt(i + 3)));  
  131.   
  132.             os.write((tri >> 16) & 255);  
  133.             if (s.charAt(i + 2) == '=')  
  134.                 break;  
  135.             os.write((tri >> 8) & 255);  
  136.             if (s.charAt(i + 3) == '=')  
  137.                 break;  
  138.             os.write(tri & 255);  
  139.   
  140.             i += 4;  
  141.         }  
  142.     }  
  143. }  

android常用加密算法之AES加密算法:

 

    1. package com.long;  
    2.   
    3. import java.security.SecureRandom;  
    4.   
    5. import javax.crypto.Cipher;  
    6. import javax.crypto.KeyGenerator;  
    7. import javax.crypto.SecretKey;  
    8. import javax.crypto.spec.SecretKeySpec;  
    9.   
    10. /** 
    11.  * AES加密解密算法 
    12.  *  
    13.  * @author long 
    14.  *  
    15.  */  
    16. public class Encryption {  
    17.   
    18.     private final static String HEX = "0123456789ABCDEF";  
    19.   
    20.     public static String encrypt(String seed, String cleartext)  
    21.             throws Exception {  
    22.         byte[] rawKey = getRawKey(seed.getBytes());  
    23.         byte[] result = encrypt(rawKey, cleartext.getBytes());  
    24.         return toHex(result);  
    25.     }  
    26.   
    27.     public static String decrypt(String seed, String encrypted)  
    28.             throws Exception {  
    29.         byte[] rawKey = getRawKey(seed.getBytes());  
    30.         byte[] enc = toByte(encrypted);  
    31.         byte[] result = decrypt(rawKey, enc);  
    32.         return new String(result);  
    33.     }  
    34.   
    35.     private static byte[] getRawKey(byte[] seed) throws Exception {  
    36.         KeyGenerator kgen = KeyGenerator.getInstance("AES");  
    37.         SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");  
    38.         sr.setSeed(seed);  
    39.         kgen.init(128, sr); // 192 and 256 bits may not be available  
    40.         SecretKey skey = kgen.generateKey();  
    41.         byte[] raw = skey.getEncoded();  
    42.         return raw;  
    43.     }  
    44.   
    45.     private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {  
    46.         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
    47.         Cipher cipher = Cipher.getInstance("AES");  
    48.         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
    49.         byte[] encrypted = cipher.doFinal(clear);  
    50.         return encrypted;  
    51.     }  
    52.   
    53.     private static byte[] decrypt(byte[] raw, byte[] encrypted)  
    54.             throws Exception {  
    55.         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
    56.         Cipher cipher = Cipher.getInstance("AES");  
    57.         cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
    58.         byte[] decrypted = cipher.doFinal(encrypted);  
    59.         return decrypted;  
    60.     }  
    61.   
    62.     public static String toHex(String txt) {  
    63.         return toHex(txt.getBytes());  
    64.     }  
    65.   
    66.     public static String fromHex(String hex) {  
    67.         return new String(toByte(hex));  
    68.     }  
    69.   
    70.     public static byte[] toByte(String hexString) {  
    71.         int len = hexString.length() / 2;  
    72.         byte[] result = new byte[len];  
    73.         for (int i = 0; i < len; i++)  
    74.             result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),  
    75.                     16).byteValue();  
    76.         return result;  
    77.     }  
    78.   
    79.     public static String toHex(byte[] buf) {  
    80.         if (buf == null)  
    81.             return "";  
    82.         StringBuffer result = new StringBuffer(2 * buf.length);  
    83.         for (int i = 0; i < buf.length; i++) {  
    84.             appendHex(result, buf[i]);  
    85.         }  
    86.         return result.toString();  
    87.     }  
    88.   
    89.     private static void appendHex(StringBuffer sb, byte b) {  
    90.         sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));  
    91.     }  

原文地址:https://www.cnblogs.com/nimorl/p/2916910.html