今天在做项目的时候遇到一个问题,我需要在ios端把上传数据加密,防止中间代理捕获信息内容并修改数据库的信息。把数据传到后台在解码,实现数据安全。
下面介绍我实现的在nodejs的加密和解密的代码希望对需要解决相同问题的有一定的帮助。
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);
};
router.get('/', function(req, res) {
test_des({
alg: 'des-cbc',
autoPad: true,
key: '20120401',
plaintext: 'abcd',
iv: "12345678"
});
res.render('index', { title: 'Express' });
});
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);
}
}
来源:oschina
链接:https://my.oschina.net/u/1582832/blog/305294