關於 Des加密(Android與ios 與後臺java服務器之間的加密解密)

最近作了一個移動項目,是有服務器和客戶端類型的項目,客戶端是要登陸才行的,登陸的密碼要用DES加密,服務器是用Java開發的,客戶端要同時支持多 平臺(Android、iOS),在處理iOS的DES加密的時候遇到了一些問題,起初怎麼調都調不成和Android端生成的密文相同。最終一個突然的想法讓我找到了問題的所在,如今將代碼總結一下,以備本身之後查閱。java

首先,Java端的DES加密的實現方式,代碼以下:算法

public class DES {
    private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    public static String encryptDES(String encryptString, String encryptKey)
            throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
        return Base64.encode(encryptedData);
    }
}

上述代碼用到了一個Base64的編碼類,其代碼的實現方式以下:數組

public class Base64 {
    
    private static final char[] legalChars = "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 >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);
            i += 3;
            if (n++ >= 14) {
                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 >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 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 >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }
        return buf.toString();
    }
}

以上即是Java端的DES加密方法的所有實現過程。服務器

我還編寫了一個將byte的二進制轉換成16進制的方法,以便調試的時候使用打印輸出加密後的byte數組的內容,這個方法不是加密的部分,只是爲調試而使用的:app

public static String parseByte2HexStr(byte buf[]) {  
    StringBuffer sb = new StringBuffer();  
    for (int i = 0; i < buf.length; i++) {  
        String hex = Integer.toHexString(buf[i] & 0xFF);  
        if (hex.length() == 1) {  
            hex = '0' + hex;  
        }  
        sb.append(hex.toUpperCase());  
    }  
    return sb.toString();  
}

下面是Objective-c在iOS上實現的DES加密算法:測試

static Byte iv[] = {1,2,3,4,5,6,7,8};

+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key{

    NSString *ciphertext = nil;
    const char *textBytes = [plainText UTF8String];
    NSUInteger dataLength = [plainText length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                  kCCOptionPKCS7Padding,
                                  [key UTF8String], kCCKeySizeDES,
                                  iv,
                                  textBytes, dataLength,
                                  buffer, 1024,
                                  &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        ciphertext = [data base64Encoding];
    }
    return ciphertext;
}

下面是一個關鍵的類:NSData的Category實現,關於Category的實現網上不少說明再也不講述。
編碼

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

- (NSString *)base64Encoding;
{
    if (self.length == 0)
        return @"";
    char *characters = malloc(self.length*3/2);
    if (characters == NULL)
        return @"";
    int end = self.length - 3;
    int index = 0;
    int charCount = 0;
    int n = 0;
    while (index <= end) {
        int d = (((int)(((char *)[self bytes])[index]) & 0x0ff) << 16) 
        | (((int)(((char *)[self bytes])[index + 1]) & 0x0ff) << 8)
        | ((int)(((char *)[self bytes])[index + 2]) & 0x0ff);
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = encodingTable[(d >> 6) & 63];
        characters[charCount++] = encodingTable[d & 63];
        index += 3;
        if(n++ >= 14){
            n = 0;
            characters[charCount++] = ' ';
        }
    }
    if(index == self.length - 2) {
        int d = (((int)(((char *)[self bytes])[index]) & 0x0ff) << 16) 
        | (((int)(((char *)[self bytes])[index + 1]) & 255) << 8);
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = encodingTable[(d >> 6) & 63];
        characters[charCount++] = '=';
    }else if(index == self.length - 1){
        int d = ((int)(((char *)[self bytes])[index]) & 0x0ff) << 16;
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = '=';
        characters[charCount++] = '=';
    }
    NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
    return rtnStr;
}

這個方法和java端的那個Base64的encode方法基本上是一個算法,只是根據語言的特色不一樣有少量的改動。加密

下面也是Objective-c的一個二進制轉換爲16進制的方法,也是爲了測試方便查看寫的:調試

+(NSString *) parseByte2HexString:(Byte *) bytes
{
    NSMutableString *hexStr = [[NSMutableString alloc]init];
    int i = 0;
    if(bytes) {
        while (bytes[i] != '\0')  {
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16進制數
            if([hexByte length]==1)
                [hexStr appendFormat:@"0%@", hexByte];
            else 
                [hexStr appendFormat:@"%@", hexByte];
            i++;
        }
    }
    NSLog(@"bytes 的16進制數爲:%@",hexStr);
    return hexStr;
}
+(NSString *) parseByteArray2HexString:(Byte[]) bytes
{
    NSMutableString *hexStr = [[NSMutableString alloc]init];
    int i = 0;
    if(bytes) {
        while (bytes[i] != '\0')   {
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16進制數
            if([hexByte length]==1)
                [hexStr appendFormat:@"0%@", hexByte];
            else 
                [hexStr appendFormat:@"%@", hexByte];
            i++;
        }
    }
    NSLog(@"bytes 的16進制數爲:%@",hexStr);
    return hexStr;
}

以上的加密方法所在的包是CommonCrypto/CommonCryptor.h。

以上便實現了Objective-c和Java下在相同的明文和密鑰的狀況下生成相同明文的算法。code

Base64的算法能夠用大家本身寫的那個,不必定必須使用我提供的這個。解密的時候還要用Base64進行密文的轉換。

 

個人解密算法以下:

private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };    

public static String decryptDES(String decryptString, String decryptKey)
         throws Exception {
     byte[] byteMi = Base64.decode(decryptString);
     IvParameterSpec zeroIv = new IvParameterSpec(iv);
     SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
     Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
     cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
     byte decryptedData[] = cipher.doFinal(byteMi);
     return new String(decryptedData);
}

Base64的decode方法以下:

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;
    } 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)) << 18)
                + (decode(s.charAt(i + 1)) << 12)
                + (decode(s.charAt(i + 2)) << 6)
                + (decode(s.charAt(i + 3)));
   
        os.write((tri >> 16) & 255);
        if (s.charAt(i + 2) == '=')
            break;
        os.write((tri >> 8) & 255);
        if (s.charAt(i + 3) == '=')
            break;
        os.write(tri & 255);
        i += 4;
    }
}
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);
        }
}

以上便實現了DES加密後的密文的解密。

Java端的測試代碼以下:

String plaintext = "abcd";
String ciphertext = DES.encryptDES(plaintext, "20120401");
System.out.println("明文:" + plaintext);
System.out.println("密鑰:" + "20120401");
System.out.println("密文:" + ciphertext);
System.out.println("解密後:" + DES.decryptDES(ciphertext, "20120401"));

輸出結果:

明文:abcd
密鑰:20120401
密文:W7HR43/usys=
解密後:abcd

Objective-c端的測試代碼以下:

NSString *plaintext = @"abcd";
NSString *ciphertext = [EncryptUtil encryptUseDES:plaintext key:@"20120401"];
NSLog(@"明文:%@",plaintext);
NSLog(@"祕鑰:%@",@"20120401");
NSLog(@"密文:%@",ciphertext);

輸出結果:

2012-04-05 12:00:47.348 TestEncrypt[806:f803] 明文:abcd
2012-04-05 12:00:47.350 TestEncrypt[806:f803] 祕鑰:20120401
2012-04-05 12:00:47.350 TestEncrypt[806:f803] 密文:W7HR43/usys=
相關文章
相關標籤/搜索