标签:
遇到一个项目,需要用AES加密密码,android的已经写好了,java源码:
private static final String AES_OPTIONS = "AES/ECB/PKCS5Padding"; private final static String CHARSET = "utf-8"; public static String encryptAES(String plain, String key) { try { Cipher cipher = Cipher.getInstance(AES_OPTIONS); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(CHARSET), "AES")); return Base64.encodeToString( cipher.doFinal(plain.getBytes(CHARSET)), Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); return null; } }
然后,我这里也需要进行AES加密,加密的key我和android都是一样的,但是加密相同的"123456"却不一样,
正确的:xPUZM4ZE0UiRP4KN4y6IPg==
贴一下IOS AES加密代码:
//将string转成带密码的data + (NSString*)encryptAESData:(NSString*)string app_key:(NSString*)key ;
#pragma mark - AES加密 //将string转成带密码的data +(NSString*)encryptAESData:(NSString*)string app_key:(NSString*)key { //将nsstring转化为nsdata NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; //使用密码对nsdata进行加密 NSData *encryptedData = [data AES128EncryptWithKey:key]; NSLog(@"加密后的字符串 :%@",[encryptedData base64EncodedString]); return [encryptedData base64EncodedString]; }
#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>
#define gIv @"AES" //可以自行修改
-(NSData *)AES128EncryptWithKey:(NSString *)key {//加密 char keyPtr[kCCKeySizeAES128+1]; bzero(keyPtr, sizeof(keyPtr)); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; char ivPtr[kCCKeySizeAES128+1]; memset(ivPtr, 0, sizeof(ivPtr)); [gIv getCString:ivPtr maxLength:sizeof(ivPtr) 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, ivPtr, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted); if (cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; } free(buffer); return nil; }
在最底层的方法中:
-(NSData *)AES128EncryptWithKey:(NSString *)key {//加密
有个
gIv的参数,这里的
1、gIv一定要改成 java代码中的“AES”,
2、由于IOS没有填充算法 PKCS5Padding ,所以在IOS要这样写:kCCOptionPKCS7Padding|kCCOptionECBMode,
基本改动就是这样。
标签:
原文地址:http://www.cnblogs.com/niit-soft-518/p/4488404.html