今天在作項目的時候遇到一個問題,我須要在ios端把上傳數據加密,防止中間代理捕獲信息內容並修改數據庫的信息。把數據傳到後臺在解碼,實現數據安全。html
下面介紹我實現的在nodejs的加密和解密的代碼但願對須要解決相同問題的有必定的幫助。java
var assert = require('assert');
var crypto = require('crypto');
function test_des(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var plaintext = param.plaintext
var alg = param.alg
var autoPad = param.autoPad
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad) //default true
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');
console.log(alg, ciph)
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad)
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');
assert.equal(txt, plaintext, 'fail');
console.log(txt);
};node
router.get('/', function(req, res) {
test_des({
alg: 'des-cbc',
autoPad: true,
key: '20120401',
plaintext: 'abcd',
iv: "12345678"
});
res.render('index', { title: 'Express' });ios
});web
ios端的加密解密代碼算法
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key { NSString *ciphertext = nil; *textBytes = [plainText UTF8String]; NSUInteger dataLength = [plainText length]; unsigned buffer[]; memset(buffer, , ()); size_t numBytesEncrypted = ; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, [@"12345678" UTF8String], textBytes, dataLength, buffer, , &numBytesEncrypted); (cryptStatus == kCCSuccess) { NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted]; ciphertext = [data base64Encoding]; } ciphertext; }
下面是一個關鍵的類:NSData的Category實現,關於Category的實現網上不少說明再也不講述。數據庫
encodingTable[] = ; - (NSString *)base64Encoding; { (self.length == ) ; *characters = malloc(self.length*/); (characters == NULL) ; end = self.length - ; index = ; charCount = ; n = ; (index <= end) { d = ((()((( *)[self bytes])[index]) & ) << ) | ((()((( *)[self bytes])[index + ]) & ) << ) | (()((( *)[self bytes])[index + ]) & ); characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[d & ]; index += ; (n++ >= ) { n = ; characters[charCount++] = ; } } (index == self.length - ) { d = ((()((( *)[self bytes])[index]) & ) << ) | ((()((( *)[self bytes])[index + ]) & ) << ); characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = ; } (index == self.length - ) { d = (()((( *)[self bytes])[index]) & ) << ; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = encodingTable[(d >> ) & ]; characters[charCount++] = ; characters[charCount++] = ; } NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES]; rtnStr; }
這個方法和java端的那個Base64的encode方法基本上是一個算法,只是根據語言的特色不一樣有少量的改動。數組
下面也是Objective-c的一個二進制轉換爲16進制的方法,也是爲了測試方便查看寫的:安全
+(NSString *) parseByte2HexString:(Byte *) bytes { NSMutableString *hexStr = [[NSMutableString alloc]init]; i = ; (bytes) { (bytes[i] != ) { NSString *hexByte = [NSString stringWithFormat:,bytes[i] & ]; ([hexByte length]==) [hexStr appendFormat:, hexByte]; [hexStr appendFormat:, hexByte]; i++; } } NSLog(,hexStr); hexStr; } +(NSString *) parseByteArray2HexString[object Object]:(Byte[]) bytes { NSMutableString *hexStr = [[NSMutableString alloc]init]; i = ; (bytes) { (bytes[i] != ) { NSString *hexByte = [NSString stringWithFormat:,bytes[i] & ]; ([hexByte length]==) [hexStr appendFormat:, hexByte]; [hexStr appendFormat:, hexByte]; i++; } } NSLog(,hexStr); hexStr; }
以上的加密方法所在的包是CommonCrypto/CommonCryptor.h。
以上便實現了Objective-c和Java下在相同的明文和密鑰的狀況下生成相同明文的算法。服務器
Base64的算法能夠用大家本身寫的那個,不必定必須使用我提供的這個。解密的時候還要用Base64進行密文的轉換。
還有借鑑別人編寫的java代碼
首先,Java端的DES加密的實現方式,代碼以下:
DES { [] iv = { , , , , , , , }; String encryptDES(String encryptString, String encryptKey) throws Exception { IvParameterSpec zeroIv = IvParameterSpec(iv); SecretKeySpec key = SecretKeySpec(encryptKey.getBytes(), ); Cipher cipher = Cipher.getInstance(); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); [] encryptedData = cipher.doFinal(encryptString.getBytes()); Base64.encode(encryptedData); } }
上述代碼用到了一個Base64的編碼類,其代碼的實現方式以下:
Base64 { [] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWX[object Object]YZabcdefghijklmnopqrstuv[object Object]wxyz0123456789+/" .toCharArray(); String encode([] data) { start = 0; len = data.length; StringBuffer buf = StringBuffer(data.length * 3 / 2); end = len - 3; i = start; n = 0; (i <= end) { d = (((() data[i]) & 0x0ff) << 16) | (((() data[i + 1]) & 0x0ff) << 8) | ((() 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; (n++ >= 14) { n = 0; buf.append(" "); } } (i == start + len - 2) { d = (((() data[i]) & 0x0ff) << 16) | (((() 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("="); } (i == start + len - 1) { d = ((() data[i]) & 0x0ff) << 16; buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append("=="); } buf.toString(); } }
以上即是Java端的DES加密方法的所有實現過程。
我還編寫了一個將byte的二進制轉換成16進制的方法,以便調試的時候使用打印輸出加密後的byte數組的內容,這個方法不是加密的部分,只是爲調試而使用的:
String parseByte2HexStr( buf[]) { StringBuffer sb = StringBuffer(); ( i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } sb.toString(); }
個人解密算法以下:
[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; String decryptDES(String decryptString, String decryptKey) Exception { [] byteMi = Base64.decode(decryptString); IvParameterSpec zeroIv = IvParameterSpec(iv); SecretKeySpec key = SecretKeySpec(decryptKey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, zeroIv); decryptedData[] = cipher.doFinal(byteMi); String(decryptedData); }
Base64的decode方法以下:
[] decode(String s) { ByteArrayOutputStream bos = ByteArrayOutputStream(); { decode(s, bos); } (IOException e) { RuntimeException(); } [] decodedBytes = bos.toByteArray(); { bos.close(); bos = ; } (IOException ex) { System.err.println("Error while decoding BASE64: " + ex.toString()); } decodedBytes; } decode(String s, OutputStream os) IOException { i = 0; len = s.length(); () { (i < len && s.charAt(i) <= ' ') i++; (i == len) ; 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); (s.charAt(i + 2) == '=') ; os.write((tri >> 8) & 255); (s.charAt(i + 3) == '=') ; os.write(tri & 255); i += 4; } } decode( c) { (c >= 'A' && c <= 'Z') (() c) - 65; (c >= 'a' && c <= 'z') (() c) - 97 + 26; (c >= '0' && c <= '9') (() c) - 48 + 26 + 26; (c) { '+': 62; '/': 63; '=': 0; : RuntimeException("unexpected code: " + c); } }