十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
之前在项目上用到AES256加密解密算法,刚开始在java端加密解密都没有问题,在iOS端加密解密也没有问题。但是奇怪的是在java端加密后的文件在iOS端无法正确解密打开,然后简单测试了一下,发现在java端和iOS端采用相同明文,相同密钥加密后的密文不一样!上网查了资料后发现iOS中AES加密算法采用的填充是PKCS7Padding,而java不支持PKCS7Padding,只支持PKCS5Padding。我们知道加密算法由算法+模式+填充组成,所以这两者不同的填充算法导致相同明文相同密钥加密后出现密文不一致的情况。那么我们需要在java中用PKCS7Padding来填充,这样就可以和iOS端填充算法一致了。
在临湘等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都做网站、网站建设 网站设计制作按需定制开发,公司网站建设,企业网站建设,成都品牌网站建设,全网营销推广,外贸网站建设,临湘网站建设费用合理。
要实现在java端用PKCS7Padding填充,需要用到bouncycastle组件来实现,下面我会提供该包的下载。啰嗦了一大堆,下面是一个简单的测试,上代码!
001 package com.encrypt.file;
002
003
004 import java.io.UnsupportedEncodingException;
005 importjava.security.Key;
006 import java.security.Security;
007
008 importjavax.crypto.Cipher;
009 importjavax.crypto.SecretKey;
010 importjavax.crypto.spec.SecretKeySpec;
011
012 public classAES256Encryption{
013
014 /**
015 * 密钥算法
016 * java6支持56位密钥,bouncycastle支持64位
017 * */
018 public static finalString KEY_ALGORITHM="AES";
019
020 /**
021 * 加密/解密算法/工作模式/填充方式
022 *
023 * JAVA6 支持PKCS5PADDING填充方式
024 * Bouncy castle支持PKCS7Padding填充方式
025 * */
026 public static finalString CIPHER_ALGORITHM="AES/ECB/PKCS7Padding";
027
028 /**
029 *
030 * 生成密钥,java6只支持56位密钥,bouncycastle支持64位密钥
031 * @return byte[] 二进制密钥
032 * */
033 public static byte[] initkey() throwsException{
034
035 // //实例化密钥生成器
036 // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
037 // KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC");
038 // //初始化密钥生成器,AES要求密钥长度为128位、192位、256位
039 //// kg.init(256);
040 // kg.init(128);
041 // //生成密钥
042 // SecretKey secretKey=kg.generateKey();
043 // //获取二进制密钥编码形式
044 // return secretKey.getEncoded();
045 //为了便于测试,这里我把key写死了,如果大家需要自动生成,可用上面注释掉的代码
046 return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,
047 0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f,
048 0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09,
049 0x06, 0x07, 0x09, 0x0d };
050 }
051
052 /**
053 * 转换密钥
054 * @param key 二进制密钥
055 * @return Key 密钥
056 * */
057 public static Key toKey(byte[] key) throwsException{
058 //实例化DES密钥
059 //生成密钥
060 SecretKey secretKey=newSecretKeySpec(key,KEY_ALGORITHM);
061 returnsecretKey;
062 }
063
064 /**
065 * 加密数据
066 * @param data 待加密数据
067 * @param key 密钥
068 * @return byte[] 加密后的数据
069 * */
070 public static byte[] encrypt(byte[] data,byte[] key) throwsException{
071 //还原密钥
072 Key k=toKey(key);
073 /**
074 * 实例化
075 * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
076 * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
077 */
078 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
079 Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC");
080 //初始化,设置为加密模式
081 cipher.init(Cipher.ENCRYPT_MODE, k);
082 //执行操作
083 returncipher.doFinal(data);
084 }
085 /**
086 * 解密数据
087 * @param data 待解密数据
088 * @param key 密钥
089 * @return byte[] 解密后的数据
090 * */
091 public static byte[] decrypt(byte[] data,byte[] key) throwsException{
092 //欢迎密钥
093 Key k =toKey(key);
094 /**
095 * 实例化
096 * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
097 * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
098 */
099 Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
100 //初始化,设置为解密模式
101 cipher.init(Cipher.DECRYPT_MODE, k);
102 //执行操作
103 returncipher.doFinal(data);
104 }
105 /**
106 * @param args
107 * @throws UnsupportedEncodingException
108 * @throws Exception
109 */
110 public static void main(String[] args) throwsUnsupportedEncodingException{
111
112 String str="AES";
113 System.out.println("原文:"+str);
114
115 //初始化密钥
116 byte[] key;
117 try {
118 key = AES256Encryption.initkey();
119 System.out.print("密钥:");
120 for(int i = 0;ikey.length;i++){
121 System.out.printf("%x", key[i]);
122 }
123 System.out.print("\n");
124 //加密数据
125 byte[] data=AES256Encryption.encrypt(str.getBytes(), key);
126 System.out.print("加密后:");
127 for(int i = 0;idata.length;i++){
128 System.out.printf("%x", data[i]);
129 }
130 System.out.print("\n");
131
132 //解密数据
133 data=AES256Encryption.decrypt(data, key);
134 System.out.println("解密后:"+newString(data));
135 } catch (Exception e) {
136 // TODO Auto-generated catch block
137 e.printStackTrace();
138 }
139
140 }
141 }
运行程序后的结果截图:
ViewController.m文件
01 //
02 // ViewController.m
03 // AES256EncryptionDemo
04 //
05 // Created by 孙 裔 on 12-12-13.
06 // Copyright (c) 2012年 rich sun. All rights reserved.
07 //
08
09 #import "ViewController.h"
10 #import "EncryptAndDecrypt.h"
11
12 @interface ViewController ()
13
14 @end
15
16 @implementation ViewController
17 @synthesize plainTextField;
18 - (void)viewDidLoad
19 {
20 [super viewDidLoad];
21 // Do any additional setup after loading the view, typically from a nib.
22 }
23
24 - (void)didReceiveMemoryWarning
25 {
26 [super didReceiveMemoryWarning];
27 // Dispose of any resources that can be recreated.
28 }
29 //这个函数实现了用户输入完后点击视图背景,关闭键盘
30 - (IBAction)backgroundTap:(id)sender{
31 [plainTextField resignFirstResponder];
32 }
33
34 - (IBAction)encrypt:(id)sender {
35
36 NSString *plainText = plainTextField.text;//明文
37 NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
38
39 //为了测试,这里先把密钥写死
40 Byte keyByte[] = {0x08,0x08,0x04,0x0b,0x02,0x0f,0x0b,0x0c,0x01,0x03,0x09,0x07,0x0c,0x03,
41 0x07,0x0a,0x04,0x0f,0x06,0x0f,0x0e,0x09,0x05,0x01,0x0a,0x0a,0x01,0x09,
42 0x06,0x07,0x09,0x0d};
43 //byte转换为NSData类型,以便下边加密方法的调用
44 NSData *keyData = [[NSData alloc] initWithBytes:keyByte length:32];
45 //
46 NSData *cipherTextData = [plainTextData AES256EncryptWithKey:keyData];
47 Byte *plainTextByte = (Byte *)[cipherTextData bytes];
48 for(int i=0;i[cipherTextData length];i++){
49 printf("%x",plainTextByte[i]);
50 }
51
52 }
53 @end
附上出处链接:
头文件
#import CommonCrypto/CommonCryptor.h
NSString *const kInitVector = @"ffGGtsdfzxCv5568";
NSString *const DESKey = @"gg356tt8g5h6j9jh";
+ (NSString *)encodeDesWithString:(NSString *)str{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
size_t plainTextBufferSize = [data length];
const void *vplainText = (const void *)[data bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) ~(kCCBlockSizeDES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) [DESKey UTF8String];
const void *vinitVec = (const void *) [kInitVector UTF8String];
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySizeDES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *result = [myData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return result;
}
+ (NSString *)decodeDesWithString:(NSString *)str{
NSData *encryptData = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
size_t plainTextBufferSize = [encryptData length];
const void *vplainText = [encryptData bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) ~(kCCBlockSizeDES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) [DESKey UTF8String];
const void *vinitVec = (const void *) [kInitVector UTF8String];
ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySizeDES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
movedBytes);
NSString *result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding];
return result;
}
在开发中经常会遇到数据的加密,常见的有base64、DES、AES、RSA等,由于AES的用法相对简单一些,在公司的项目中,我们使用的是AES加密。但是遇到一个大坑就是后台使用了AES的128/CBC/NoPadding加密模式,很可悲的是iOS中只有PKCS7Padding和PKCS5Padding这两种模式,没有NoPadding模式。经过各种百度、谷歌后,终于发现了一篇文章解决了这个问题。
下面是参考文章的链接 :
问题就处在No Padding. No Pading的情况下,一定要对加密数据不是kCCKeySizeAES128倍数部分进行0x0000的填充,不然加密长度不正确,一般情况下选择使用kCCOptionPKCS7Padding(也就是0x0001)进行填充,但是我们是No Padding所以要用 0x0000 填充。
#region 跨平台加解密(c# 安卓 IOS)
// public static string sKey = "12345678";
// /// summary
// /// 解密
// /// /summary
// /// param name="pToDecrypt"要解密的以Base64/param
// /// param name="sKey"密钥,且必须为8位/param
// /// returns已解密的字符串/returns
// public static string DesDecrypt(string pToDecrypt)
// {
// //转义特殊字符
// pToDecrypt = pToDecrypt.Replace("-", "+");
// pToDecrypt = pToDecrypt.Replace("_", "/");
// pToDecrypt = pToDecrypt.Replace("~", "=");
// byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
// using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
// {
// des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
// des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
// System.IO.MemoryStream ms = new System.IO.MemoryStream();
// using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
// {
// cs.Write(inputByteArray, 0, inputByteArray.Length);
// cs.FlushFinalBlock();
// cs.Close();
// }
// string str = Encoding.UTF8.GetString(ms.ToArray());
// ms.Close();
// return str;
// }
// }
// /// summary
// /// 对字符串进行DES加密
// /// /summary
// /// param name="sourceString"待加密的字符串/param
// /// returns加密后的BASE64编码的字符串/returns
// public string Encrypt(string sourceString)
//{
// byte[] btKey = Encoding.UTF8.GetBytes(sKey);
// byte[] btIV = Encoding.UTF8.GetBytes(sKey);
// DESCryptoServiceProvider des = new DESCryptoServiceProvider();
// using (MemoryStream ms = new MemoryStream())
// {
// byte[] inData = Encoding.UTF8.GetBytes(sourceString);
// try
// {
// using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
// {
// cs.Write(inData, 0, inData.Length);
// cs.FlushFinalBlock();
// }
// return Convert.ToBase64String(ms.ToArray());
// }
// catch
// {
// throw;
// }
// }
//}
#endregion
安卓---------------------------------------------------------------------------
// // 加密
//public static String DecryptDoNet(String message, String key)
// throws Exception {
// byte[] bytesrc = Base64.decode(message.getBytes(), Base64.DEFAULT);
// Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
// cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
// byte[] retByte = cipher.doFinal(bytesrc);
// return new String(retByte);
//}
//// 解密
//public static String EncryptAsDoNet(String message, String key)
// throws Exception {
// Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
// cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
// byte[] encryptbyte = cipher.doFinal(message.getBytes());
// return new String(Base64.encode(encryptbyte, Base64.DEFAULT));
//}
Ios --------------------------------------------------------------------------------------------------------------------\
static const char* encryptWithKeyAndType(const char *text,CCOperation encryptOperation,char *key)
{
NSString *textString=[[NSString alloc]initWithCString:text encoding:NSUTF8StringEncoding];
// NSLog(@"[[item.url description] UTF8String=%@",textString);
const void *dataIn;
size_t dataInLength;
if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码
{
//解码 base64
NSData *decryptData = [GTMBase64 decodeData:[textString dataUsingEncoding:NSUTF8StringEncoding]];//转成utf-8并decode
dataInLength = [decryptData length];
dataIn = [decryptData bytes];
}
else //encrypt
{
NSData* encryptData = [textString dataUsingEncoding:NSUTF8StringEncoding];
dataInLength = [encryptData length];
dataIn = (const void *)[encryptData bytes];
}
CCCryptorStatus ccStatus;
uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)
size_t dataOutAvailable = 0; //size_t 是操作符sizeof返回的结果类型
size_t dataOutMoved = 0;
dataOutAvailable = (dataInLength + kCCBlockSizeDES) ~(kCCBlockSizeDES - 1);
dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
memset((void *)dataOut, 00, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0
//NSString *initIv = @"12345678";
const void *vkey = key;
const void *iv = (const void *) key; //[initIv UTF8String];
//CCCrypt函数 加密/解密
ccStatus = CCCrypt(encryptOperation,// 加密/解密
kCCAlgorithmDES,// 加密根据哪个标准(des,3des,aes。。。。)
kCCOptionPKCS7Padding,// 选项分组密码算法(des:对每块分组加一次密 3DES:对每块分组加三个不同的密)
vkey, //密钥 加密和解密的密钥必须一致
kCCKeySizeDES,// DES 密钥的大小(kCCKeySizeDES=8)
iv, // 可选的初始矢量
dataIn, // 数据的存储单元
dataInLength,// 数据的大小
(void *)dataOut,// 用于返回数据
dataOutAvailable,
dataOutMoved);
NSString *result = nil;
if (encryptOperation == kCCDecrypt)//encryptOperation==1 解码
{
//得到解密出来的data数据,改变为utf-8的字符串
result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding];
}
else //encryptOperation==0 (加密过程中,把加好密的数据转成base64的)
{
//编码 base64
NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
result = [GTMBase64 stringByEncodingData:data];
}
return [result UTF8String];
}
+(NSString*)encryptWithContent:(NSString*)content type:(CCOperation)type key:(NSString*)aKey
{
const char * contentChar =[content UTF8String];
char * keyChar =(char*)[aKey UTF8String];
const char *miChar;
miChar = encryptWithKeyAndType(contentChar, type, keyChar);
return [NSString stringWithCString:miChar encoding:NSUTF8StringEncoding];
}
5.1 通过简单的URLENCODE + BASE64编码防止数据明文传输
5.2 对普通请求、返回数据,生成MD5校验(MD5中加入动态密钥),进行数据完整性(简单防篡改,安全性较低,优点:快速)校验。
5.3 对于重要数据,使用RSA进行数字签名,起到防篡改作用。
5.4 对于比较敏感的数据,如用户信息(登陆、注册等),客户端发送使用RSA加密,服务器返回使用DES(AES)加密。
原因:客户端发送之所以使用RSA加密,是因为RSA解密需要知道服务器私钥,而服务器私钥一般盗取难度较大;如果使用DES的话,可以通过破解客户端获取密钥,安全性较低。而服务器返回之所以使用DES,是因为不管使用DES还是RSA,密钥(或私钥)都存储在客户端,都存在被破解的风险,因此,需要采用动态密钥,而RSA的密钥生成比较复杂,不太适合动态密钥,并且RSA速度相对较慢,所以选用DES)
把相关算法的代码也贴一下吧 (其实使用一些成熟的第三方库或许会来得更加简单,不过自己写,自由点)。注,这里的大部分加密算法都是参考一些现有成熟的算法,或者直接拿来用的。
1、MD5
//因为是使用category,所以木有参数传入啦
-(NSString *) stringFromMD5 {
if(self == nil || [self length] == 0) {
return nil;
}
const char *value = [self UTF8String];
unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(value, strlen(value), outputBuffer);
NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(NSInteger count = 0; count CC_MD5_DIGEST_LENGTH; count++){
[outputString appendFormat:@"%02x",outputBuffer[count]];
}
return [outputString autorelease];
}
2、Base64
+ (NSString *) base64EncodeData: (NSData *) objData {
const unsigned char * objRawData = [objData bytes];
char * objPointer;
char * strResult;
// Get the Raw Data length and ensure we actually have data
int intLength = [objData length];
if (intLength == 0) return nil;
// Setup the String-based Result placeholder and pointer within that placeholder
strResult = (char *)calloc(((intLength + 2) / 3) * 4, sizeof(char));
objPointer = strResult;
// Iterate through everything
while (intLength 2) { // keep going until we have less than 24 bits
*objPointer++ = _base64EncodingTable[objRawData[0] 2];
*objPointer++ = _base64EncodingTable[((objRawData[0] 0x03) 4) + (objRawData[1] 4)];
*objPointer++ = _base64EncodingTable[((objRawData[1] 0x0f) 2) + (objRawData[2] 6)];
*objPointer++ = _base64EncodingTable[objRawData[2] 0x3f];
// we just handled 3 octets (24 bits) of data
objRawData += 3;
intLength -= 3;
}
// now deal with the tail end of things
if (intLength != 0) {
*objPointer++ = _base64EncodingTable[objRawData[0] 2];
if (intLength 1) {
*objPointer++ = _base64EncodingTable[((objRawData[0] 0x03) 4) + (objRawData[1] 4)];
*objPointer++ = _base64EncodingTable[(objRawData[1] 0x0f) 2];
*objPointer++ = '=';
} else {
*objPointer++ = _base64EncodingTable[(objRawData[0] 0x03) 4];
*objPointer++ = '=';
*objPointer++ = '=';
}
}
// Terminate the string-based result
*objPointer = '\0';
NSString *rstStr = [NSString stringWithCString:strResult encoding:NSASCIIStringEncoding];
free(objPointer);
return rstStr;
}
3、AES
-(NSData*) EncryptAES: (NSString *) key {
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[self bytes], dataLength,
buffer, bufferSize,
numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
4、RSA
- (NSData *) encryptWithData:(NSData *)content {
size_t plainLen = [content length];
if (plainLen maxPlainLen) {
NSLog(@"content(%ld) is too long, must %ld", plainLen, maxPlainLen);
return nil;
}
void *plain = malloc(plainLen);
[content getBytes:plain
length:plainLen];
size_t cipherLen = 128; // currently RSA key length is set to 128 bytes
void *cipher = malloc(cipherLen);
OSStatus returnCode = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, plain,
plainLen, cipher, cipherLen);
NSData *result = nil;
if (returnCode != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %ld", returnCode);
}
else {
result = [NSData dataWithBytes:cipher
length:cipherLen];
}
free(plain);
free(cipher);
return result;
}