zoukankan      html  css  js  c++  java
  • PHP、JAVA、C#、Object-C 通用的DES加密

    php:

     1 class JoDES {
     2  
     3     private static $_instance = NULL;
     4     /**
     5      * @return JoDES
     6      */
     7     public static function share() {
     8         if (is_null(self::$_instance)) {
     9             self::$_instance = new JoDES();
    10         }
    11         return self::$_instance;
    12     }
    13  
    14     /**
    15      * 加密
    16      * @param string $str 要处理的字符串
    17      * @param string $key 加密Key,为8个字节长度
    18      * @return string
    19      */
    20     public function encode($str, $key) {
    21         $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
    22         $str = $this->pkcs5Pad($str, $size);
    23         $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
    24         $ret = base64_encode($aaa);
    25         return $ret;
    26     }
    27  
    28     /**
    29      * 解密
    30      * @param string $str 要处理的字符串
    31      * @param string $key 解密Key,为8个字节长度
    32      * @return string
    33      */
    34     public function decode($str, $key) {
    35         $strBin = base64_decode($str);
    36         $str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key);
    37         $str = $this->pkcs5Unpad($str);
    38         return $str;
    39     }
    40  
    41     function hex2bin($hexData) {
    42         $binData = "";
    43         for ($i = 0; $i < strlen($hexData); $i += 2) {
    44             $binData .= chr(hexdec(substr($hexData, $i, 2)));
    45         }
    46         return $binData;
    47     }
    48  
    49     function pkcs5Pad($text, $blocksize) {
    50         $pad = $blocksize - (strlen($text) % $blocksize);
    51         return $text . str_repeat(chr($pad), $pad);
    52     }
    53  
    54     function pkcs5Unpad($text) {
    55         $pad = ord($text {strlen($text) - 1});
    56         if ($pad > strlen($text))
    57             return false;
    58  
    59         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
    60             return false;
    61  
    62         return substr($text, 0, - 1 * $pad);
    63     }
    64  
    65 }
    View Code

    c#:

     1 public class MyDes
     2     {
     3         /// <summary>
     4         /// DES加密方法
     5         /// </summary>
     6         /// <param name="strPlain">明文</param>
     7         /// <param name="strDESKey">密钥</param>
     8         /// <param name="strDESIV">向量</param>
     9         /// <returns>密文</returns>
    10         public static string Encode(string source, string _DESKey)
    11         {
    12             StringBuilder sb = new StringBuilder();
    13             using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
    14             {
    15                 byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey);
    16                 byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey);
    17                 byte[] dataByteArray = Encoding.UTF8.GetBytes(source);
    18                 des.Mode = System.Security.Cryptography.CipherMode.CBC;
    19                 des.Key = key;
    20                 des.IV = iv;
    21                 string encrypt = "";
    22                 using (MemoryStream ms = new MemoryStream())
    23                 using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
    24                 {
    25                     cs.Write(dataByteArray, 0, dataByteArray.Length);
    26                     cs.FlushFinalBlock();
    27                     encrypt = Convert.ToBase64String(ms.ToArray());
    28                 }
    29                 return encrypt;
    30             }
    31         }
    32  
    33         /// <summary>
    34         /// 进行DES解密。
    35         /// </summary>
    36         /// <param name="pToDecrypt">要解密的base64串</param>
    37         /// <param name="sKey">密钥,且必须为8位。</param>
    38         /// <returns>已解密的字符串。</returns>
    39         public static string Decode(string source, string sKey)
    40         {
    41             byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source);
    42             using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
    43             {
    44                 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    45                 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    46                 System.IO.MemoryStream ms = new System.IO.MemoryStream();
    47                 using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
    48                 {
    49                     cs.Write(inputByteArray, 0, inputByteArray.Length);
    50                     cs.FlushFinalBlock();
    51                     cs.Close();
    52                 }
    53                 string str = Encoding.UTF8.GetString(ms.ToArray());
    54                 ms.Close();
    55                 return str;
    56             }
    57         }
    58     }
    View Code

    Object-c:

      1 /***  JoDes.h ***/
      2  
      3 #import <Foundation/Foundation.h>
      4 #import <CommonCrypto/CommonDigest.h>
      5 #import <CommonCrypto/CommonCryptor.h>
      6  
      7 @interface JoDes : NSObject
      8  
      9 + (NSString *) encode:(NSString *)str key:(NSString *)key;
     10 + (NSString *) decode:(NSString *)str key:(NSString *)key;
     11  
     12 @end
     13  
     14  
     15 /***  JoDes.m ***/
     16 //
     17 //  XLEncrytHelper.m
     18 //  NewHoldGold
     19 //
     20 //  Created by 梁鑫磊 on 13-12-27.
     21 //  Copyright (c) 2013年 zsgjs. All rights reserved.
     22 //
     23  
     24 #import "JoDes.h"
     25  
     26 @interface JoDes()
     27  
     28 + (NSString *) encodeBase64WithString:(NSString *)strData;
     29 + (NSString *) encodeBase64WithData:(NSData *)objData;
     30 + (NSData *) decodeBase64WithString:(NSString *)strBase64;
     31  
     32 + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
     33                   context:(CCOperation)encryptOrDecrypt;
     34  
     35 @end
     36  
     37 @implementation JoDes
     38  
     39 + (NSString *) encode:(NSString *)str key:(NSString *)key
     40 {
     41     // doCipher 不能编汉字,所以要进行 url encode
     42     NSMutableString* str1 = [JoDes urlEncode:str];
     43     NSMutableString* encode = [NSMutableString stringWithString:[JoDes doCipher:str1 key:key context:kCCEncrypt]];
     44     [JoDes formatSpecialCharacters:encode];
     45     return encode;
     46 }
     47  
     48 + (NSString *) decode:(NSString *)str key:(NSString *)key
     49 {
     50     NSMutableString *str1 = [NSMutableString stringWithString:str];
     51     [JoDes reformatSpecialCharacters:str1];
     52     NSString *rt = [JoDes doCipher:str1 key:key context:kCCDecrypt];
     53     return rt;
     54 }
     55  
     56 + (NSMutableString *)urlEncode:(NSString*)str
     57 {
     58     NSMutableString* encodeStr = [NSMutableString stringWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
     59     [encodeStr replaceOccurrencesOfString:@"+" withString:@"%2B" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
     60     [encodeStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
     61     return encodeStr;
     62 }
     63  
     64 + (void)formatSpecialCharacters:(NSMutableString *)str
     65 {
     66     [str replaceOccurrencesOfString:@"+" withString:@"$$" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
     67     [str replaceOccurrencesOfString:@"/" withString:@"@@" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
     68 }
     69  
     70  
     71 + (void)reformatSpecialCharacters:(NSMutableString *)str
     72 {
     73     [str replaceOccurrencesOfString:@"$$" withString:@"+" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
     74     [str replaceOccurrencesOfString:@"@@" withString:@"/" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
     75 }
     76  
     77 + (NSString *)encodeBase64WithString:(NSString *)strData {
     78     return [JoDes encodeBase64WithData:[strData dataUsingEncoding:NSUTF8StringEncoding]];
     79 }
     80  
     81  
     82 + (NSString *)encodeBase64WithData:(NSData *)objData {
     83     NSString *encoding = nil;
     84     unsigned char *encodingBytes = NULL;
     85     @try {
     86         static char encodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     87         static NSUInteger paddingTable[] = {0,2,1};
     88          
     89         NSUInteger dataLength = [objData length];
     90         NSUInteger encodedBlocks = (dataLength * 8) / 24;
     91         NSUInteger padding = paddingTable[dataLength % 3];
     92         if( padding > 0 ) encodedBlocks++;
     93         NSUInteger encodedLength = encodedBlocks * 4;
     94          
     95         encodingBytes = malloc(encodedLength);
     96         if( encodingBytes != NULL ) {
     97             NSUInteger rawBytesToProcess = dataLength;
     98             NSUInteger rawBaseIndex = 0;
     99             NSUInteger encodingBaseIndex = 0;
    100             unsigned char *rawBytes = (unsigned char *)[objData bytes];
    101             unsigned char rawByte1, rawByte2, rawByte3;
    102             while( rawBytesToProcess >= 3 ) {
    103                 rawByte1 = rawBytes[rawBaseIndex];
    104                 rawByte2 = rawBytes[rawBaseIndex+1];
    105                 rawByte3 = rawBytes[rawBaseIndex+2];
    106                 encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
    107                 encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
    108                 encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) | ((rawByte3 >> 6) & 0x03) ];
    109                 encodingBytes[encodingBaseIndex+3] = encodingTable[(rawByte3 & 0x3F)];
    110                  
    111                 rawBaseIndex += 3;
    112                 encodingBaseIndex += 4;
    113                 rawBytesToProcess -= 3;
    114             }
    115             rawByte2 = 0;
    116             switch (dataLength-rawBaseIndex) {
    117                 case 2:
    118                     rawByte2 = rawBytes[rawBaseIndex+1];
    119                 case 1:
    120                     rawByte1 = rawBytes[rawBaseIndex];
    121                     encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
    122                     encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
    123                     encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) ];
    124                     // we can skip rawByte3 since we have a partial block it would always be 0
    125                     break;
    126             }
    127             // compute location from where to begin inserting padding, it may overwrite some bytes from the partial block encoding
    128             // if their value was 0 (cases 1-2).
    129             encodingBaseIndex = encodedLength - padding;
    130             while( padding-- > 0 ) {
    131                 encodingBytes[encodingBaseIndex++] = '=';
    132             }
    133             encoding = [[NSString alloc] initWithBytes:encodingBytes length:encodedLength encoding:NSASCIIStringEncoding];
    134         }
    135     }
    136     @catch (NSException *exception) {
    137         encoding = nil;
    138         NSLog(@"WARNING: error occured while tring to encode base 32 data: %@", exception);
    139     }
    140     @finally {
    141         if( encodingBytes != NULL ) {
    142             free( encodingBytes );
    143         }
    144     }
    145     return encoding;
    146      
    147 }
    148  
    149 + (NSData *)decodeBase64WithString:(NSString *)strBase64 {
    150     NSData *data = nil;
    151     unsigned char *decodedBytes = NULL;
    152     @try {
    153 #define __ 255
    154         static char decodingTable[256] = {
    155             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x00 - 0x0F
    156             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x10 - 0x1F
    157             __,__,__,__, __,__,__,__, __,__,__,62, __,__,__,63,  // 0x20 - 0x2F
    158             52,53,54,55, 56,57,58,59, 60,61,__,__, __, 0,__,__,  // 0x30 - 0x3F
    159             __, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,  // 0x40 - 0x4F
    160             15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__,  // 0x50 - 0x5F
    161             __,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,  // 0x60 - 0x6F
    162             41,42,43,44, 45,46,47,48, 49,50,51,__, __,__,__,__,  // 0x70 - 0x7F
    163             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x80 - 0x8F
    164             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x90 - 0x9F
    165             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xA0 - 0xAF
    166             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xB0 - 0xBF
    167             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xC0 - 0xCF
    168             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xD0 - 0xDF
    169             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xE0 - 0xEF
    170             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xF0 - 0xFF
    171         };
    172         strBase64 = [strBase64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
    173         NSData *encodedData = [strBase64 dataUsingEncoding:NSASCIIStringEncoding];
    174         unsigned char *encodedBytes = (unsigned char *)[encodedData bytes];
    175          
    176         NSUInteger encodedLength = [encodedData length];
    177         NSUInteger encodedBlocks = (encodedLength+3) >> 2;
    178         NSUInteger expectedDataLength = encodedBlocks * 3;
    179          
    180         unsigned char decodingBlock[4];
    181          
    182         decodedBytes = malloc(expectedDataLength);
    183         if( decodedBytes != NULL ) {
    184              
    185             NSUInteger i = 0;
    186             NSUInteger j = 0;
    187             NSUInteger k = 0;
    188             unsigned char c;
    189             while( i < encodedLength ) {
    190                 c = decodingTable[encodedBytes[i]];
    191                 i++;
    192                 if( c != __ ) {
    193                     decodingBlock[j] = c;
    194                     j++;
    195                     if( j == 4 ) {
    196                         decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
    197                         decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
    198                         decodedBytes[k+2] = (decodingBlock[2] << 6) | (decodingBlock[3]);
    199                         j = 0;
    200                         k += 3;
    201                     }
    202                 }
    203             }
    204              
    205             // Process left over bytes, if any
    206             if( j == 3 ) {
    207                 decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
    208                 decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
    209                 k += 2;
    210             } else if( j == 2 ) {
    211                 decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
    212                 k += 1;
    213             }
    214             data = [[NSData alloc] initWithBytes:decodedBytes length:k];
    215         }
    216     }
    217     @catch (NSException *exception) {
    218         data = nil;
    219         NSLog(@"WARNING: error occured while decoding base 32 string: %@", exception);
    220     }
    221     @finally {
    222         if( decodedBytes != NULL ) {
    223             free( decodedBytes );
    224         }
    225     }
    226     return data;
    227      
    228 }
    229  
    230  
    231 + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
    232                   context:(CCOperation)encryptOrDecrypt {
    233     NSStringEncoding EnC = NSUTF8StringEncoding;
    234      
    235     NSMutableData *dTextIn;
    236     if (encryptOrDecrypt == kCCDecrypt) {
    237         dTextIn = [[JoDes decodeBase64WithString:sTextIn] mutableCopy];
    238     }
    239     else{
    240         dTextIn = [[sTextIn dataUsingEncoding: EnC] mutableCopy];
    241     }
    242     NSMutableData * dKey = [[sKey dataUsingEncoding:EnC] mutableCopy];
    243     [dKey setLength:kCCBlockSizeDES];
    244     uint8_t *bufferPtr1 = NULL;
    245     size_t bufferPtrSize1 = 0;
    246     size_t movedBytes1 = 0;
    247     //uint8_t iv[kCCBlockSizeDES];
    248     //memset((void *) iv, 0x0, (size_t) sizeof(iv));
    249     //    Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
    250     bufferPtrSize1 = ([sTextIn length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    251     bufferPtr1 = malloc(bufferPtrSize1 * sizeof(uint8_t));
    252     memset((void *)bufferPtr1, 0x00, bufferPtrSize1);
    253      
    254     CCCrypt(encryptOrDecrypt, // CCOperation op
    255             kCCAlgorithmDES, // CCAlgorithm alg
    256             kCCOptionPKCS7Padding, // CCOptions options
    257             [dKey bytes], // const void *key
    258             [dKey length], // size_t keyLength //
    259             [dKey bytes], // const void *iv
    260             [dTextIn bytes], // const void *dataIn
    261             [dTextIn length],  // size_t dataInLength
    262             (void *)bufferPtr1, // void *dataOut
    263             bufferPtrSize1,     // size_t dataOutAvailable
    264             &movedBytes1);
    265      
    266     //[dTextIn release];
    267     //[dKey release];
    268      
    269     NSString * sResult;
    270     if (encryptOrDecrypt == kCCDecrypt){
    271         sResult = [[NSString alloc] initWithData:[NSData dataWithBytes:bufferPtr1 length:movedBytes1] encoding:EnC];
    272         free(bufferPtr1);
    273     }
    274     else {
    275         NSData *dResult = [NSData dataWithBytes:bufferPtr1 length:movedBytes1];
    276         free(bufferPtr1);
    277         sResult = [JoDes encodeBase64WithData:dResult];
    278     }
    279     return sResult;
    280 }
    281  
    282  
    283  
    284 @end
    View Code

    java:

     1 package com.example.aric.test;
     2  
     3 import javax.crypto.Cipher;
     4 import javax.crypto.SecretKey;
     5 import javax.crypto.SecretKeyFactory;
     6 import javax.crypto.spec.DESKeySpec;
     7 import javax.crypto.spec.IvParameterSpec;
     8  
     9 import android.util.Base64;
    10  
    11 public class DES {
    12  
    13     public final static String DES_KEY_STRING = "ABSujsuu";
    14      
    15     public static String encrypt(String message, String key) throws Exception {
    16         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    17  
    18         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    19  
    20         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    21         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    22         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
    23         cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    24  
    25         return encodeBase64(cipher.doFinal(message.getBytes("UTF-8")));
    26     }
    27  
    28     public static String decrypt(String message, String key) throws Exception {
    29  
    30         byte[] bytesrc = decodeBase64(message);//convertHexString(message);
    31         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    32         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    33         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    34         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    35         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
    36  
    37         cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    38  
    39         byte[] retByte = cipher.doFinal(bytesrc);
    40         return new String(retByte);
    41     }
    42  
    43     public static byte[] convertHexString(String ss) {
    44         byte digest[] = new byte[ss.length() / 2];
    45         for (int i = 0; i < digest.length; i++) {
    46             String byteString = ss.substring(2 * i, 2 * i + 2);
    47             int byteValue = Integer.parseInt(byteString, 16);
    48             digest[i] = (byte) byteValue;
    49         }
    50  
    51         return digest;
    52     }
    53  
    54     public static String toHexString(byte b[]) {
    55         StringBuffer hexString = new StringBuffer();
    56         for (int i = 0; i < b.length; i++) {
    57             String plainText = Integer.toHexString(0xff & b[i]);
    58             if (plainText.length() < 2)
    59                 plainText = "0" + plainText;
    60             hexString.append(plainText);
    61         }
    62  
    63         return hexString.toString();
    64     }
    65  
    66      
    67     public static String encodeBase64(byte[] b) {
    68         return Base64.encodeToString(b, Base64.DEFAULT);
    69     }
    70      
    71     public static byte[] decodeBase64(String base64String) {
    72         return Base64.decode(base64String, Base64.DEFAULT);
    73     }
    74 }
    View Code

     以下是另一种算法

      1 /**
      2  * Encodes a String in AES-256 with a given key
      3  *
      4  * @param context
      5  * @param password
      6  * @param text
      7  * @return String Base64 and AES encoded String
      8  */
      9 public static String encode(String keyString, String stringToEncode) throws NullPointerException {
     10     if (keyString.length() == 0 || keyString == null) {
     11         throw new NullPointerException("Please give Password");
     12     }
     13     
     14     if (stringToEncode.length() == 0 || stringToEncode == null) {
     15         throw new NullPointerException("Please give text");
     16     }
     17     
     18     try {
     19         SecretKeySpec skeySpec = getKey(keyString);
     20         byte[] clearText = stringToEncode.getBytes("UTF8");
     21         
     22         // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
     23         final byte[] iv = new byte[16];
     24         Arrays.fill(iv, (byte) 0x00);
     25         IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
     26         
     27         // Cipher is not thread safe
     28         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
     29         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
     30         
     31         String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
     32         Log.d("jacek", "Encrypted: " + stringToEncode + " -> " + encrypedValue);
     33         return encrypedValue;
     34         
     35     } catch (InvalidKeyException e) {
     36         e.printStackTrace();
     37     } catch (UnsupportedEncodingException e) {
     38         e.printStackTrace();
     39     } catch (NoSuchAlgorithmException e) {
     40         e.printStackTrace();
     41     } catch (BadPaddingException e) {
     42         e.printStackTrace();
     43     } catch (NoSuchPaddingException e) {
     44         e.printStackTrace();
     45     } catch (IllegalBlockSizeException e) {
     46         e.printStackTrace();
     47     } catch (InvalidAlgorithmParameterException e) {
     48         e.printStackTrace();
     49     }
     50     return "";
     51 }
     52  
     53 /**
     54  * Decodes a String using AES-256 and Base64
     55  *
     56  * @param context
     57  * @param password
     58  * @param text
     59  * @return desoded String
     60  */
     61 public String decode(String password, String text) throws NullPointerException {
     62     
     63     if (password.length() == 0 || password == null) {
     64         throw new NullPointerException("Please give Password");
     65     }
     66     
     67     if (text.length() == 0 || text == null) {
     68         throw new NullPointerException("Please give text");
     69     }
     70     
     71     try {
     72         SecretKey key = getKey(password);
     73         
     74         // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
     75         final byte[] iv = new byte[16];
     76         Arrays.fill(iv, (byte) 0x00);
     77         IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
     78         
     79         byte[] encrypedPwdBytes = Base64.decode(text, Base64.DEFAULT);
     80         // cipher is not thread safe
     81         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
     82         cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
     83         byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));
     84         
     85         String decrypedValue = new String(decrypedValueBytes);
     86         Log.d(LOG_TAG, "Decrypted: " + text + " -> " + decrypedValue);
     87         return decrypedValue;
     88         
     89     } catch (InvalidKeyException e) {
     90         e.printStackTrace();
     91     } catch (UnsupportedEncodingException e) {
     92         e.printStackTrace();
     93     } catch (NoSuchAlgorithmException e) {
     94         e.printStackTrace();
     95     } catch (BadPaddingException e) {
     96         e.printStackTrace();
     97     } catch (NoSuchPaddingException e) {
     98         e.printStackTrace();
     99     } catch (IllegalBlockSizeException e) {
    100         e.printStackTrace();
    101     } catch (InvalidAlgorithmParameterException e) {
    102         e.printStackTrace();
    103     }
    104     return "";
    105 }
    106  
    107 /**
    108  * Generates a SecretKeySpec for given password
    109  *
    110  * @param password
    111  * @return SecretKeySpec
    112  * @throws UnsupportedEncodingException
    113  */
    114 private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException {
    115     
    116     // You can change it to 128 if you wish
    117     int keyLength = 256;
    118     byte[] keyBytes = new byte[keyLength / 8];
    119     // explicitly fill with zeros
    120     Arrays.fill(keyBytes, (byte) 0x0);
    121     
    122     // if password is shorter then key length, it will be zero-padded
    123     // to key length
    124     byte[] passwordBytes = password.getBytes("UTF-8");
    125     int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
    126     System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
    127     SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    128     return key;
    129 }
    View Code
  • 相关阅读:
    linux基础知识-12
    linux基础知识-11
    linux基础知识-10
    安装与迁移Solo博客系统
    linux基础知识-9
    linux基础知识-8
    linux基础知识-7
    linux基础知识-6
    linux基础知识-5
    通俗解释下分布式、高并发、多线程
  • 原文地址:https://www.cnblogs.com/xiaoliu66007/p/4690310.html
Copyright © 2011-2022 走看看