小结:其实网上大部分帖子已经给出相应的代码,但你会发现加密的结果不一致。有个关键点。
const char *textBytes = [plainText UTF8String];
字符串直接转字节数组就会和java加密结果不一样。
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
用NSString 转 NSData 取字节流 和java加密结果一致。
具体代码如下
Java 部分代码
需要自己引入sun.misc.BASE64Decoder.jar
/**
* Description 根据键值进行加密
*
* @param data
* @param key 加密键byte数组
* @return
* @throws HiIPSException
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
Cipher cipher;
try {
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
} catch (Exception e) {
throw new Exception("DES加密异常" + e.toString());
}
}
执行Main方法
public static void main(String[] args) throws Exception {
String data = "加密参数值";
String key = "商户秘钥";
//签约参数加密输出
System.out.println(encrypt(data, key, "UTF-8"));
}
iOS端
#pragma mark- 加密算法
- (NSString *)encryptUseDES:(NSString *)plainText key:(NSString *)key
{
NSString *ciphertext = nil;
//const char *textBytes = [plainText UTF8String];字符串直接转字节数组就会和java加密结果不一样, 用NSString 转 NSData 取字节流 和java加密结果一致
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [textData length];
unsigned char buffer[1024];
memset(buffer, 0, sizeof(char));
Byte iv[] = {1,2,3,4,5,6,7,8};
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding|kCCOptionECBMode,
[key UTF8String], kCCKeySizeDES,
iv,
[textData bytes], dataLength,
buffer, 1024,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
}
return ciphertext;
}
#pragma mark- 解密算法
- (NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key
{
NSString *plaintext = nil;
NSData *cipherdata = [GTMBase64 decodeString:cipherText];
unsigned char buffer[1024];
memset(buffer, 0, sizeof(char));
Byte iv[] = {1,2,3,4,5,6,7,8};
size_t numBytesDecrypted = 0;
// kCCOptionPKCS7Padding|kCCOptionECBMode 最主要在这步
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding|kCCOptionECBMode,
[key UTF8String], kCCKeySizeDES,
iv,
[cipherdata bytes], [cipherdata length],
buffer, 1024,
&numBytesDecrypted);
if(cryptStatus == kCCSuccess) {
NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
}
return plaintext;
}