ios des加密与解密(对应JAVA加解密)

以下代码有添加用到hexString的转换过程

//
//  NSString+Des.h
//  DES加密
//
//  Created by NJL on 2019/9/18.
//  Copyright © 2019 Netease. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Des)
+(NSString *)des:(NSString *)str key:(NSString *)key;

+(NSString *)decryptDes:(NSString*)str key:(NSString*)key;
@end

NS_ASSUME_NONNULL_END
//
//  NSString+Des.m
//  DES加密
//
//  Created by NJL on 2019/9/18.
//  Copyright © 2019 Netease. All rights reserved.
//

#import "NSString+Des.h"
#import <CommonCrypto/CommonCryptor.h>
#import "NSData+DataToHexString.h"
@implementation NSString (Des)
+(NSString *)des:(NSString *)str key:(NSString *)key{
    NSString *ciphertext = nil;
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        NSLog(@"data = %@",data);
        ciphertext = [data dataToHexString];
        NSLog(@"ciphertext = %@",ciphertext);
    }
    return ciphertext;
}


//解密
+(NSString *)decryptDes:(NSString*)hexString key:(NSString*)key{
    NSData *data = [self hexStringToData:hexString];
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding|kCCOptionECBMode, keyPtr, kCCBlockSizeDES, NULL, [data bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
    if(cryptStatus == kCCSuccess){
        NSString *string = [[NSString alloc]initWithData:[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted] encoding:NSUTF8StringEncoding];
        NSLog(@"string = %@",string);
        return string;
    }
    free(buffer);
    return nil;
}

+(NSData *)hexStringToData:(NSString *)hexString{
    const char *chars = [hexString UTF8String];
    int i = 0;
    int len = (int)hexString.length;
    NSMutableData *data = [NSMutableData dataWithCapacity:len/2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    
    while (i<len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    return data;
}

@end

//
//  NSData+DataToHexString.h
//  DES加密
//
//  Created by NJL on 2019/9/19.
//  Copyright © 2019 Netease. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSData (DataToHexString)

-(NSString *)dataToHexString;
@end

NS_ASSUME_NONNULL_END

//
//  NSData+DataToHexString.m
//  DES加密
//
//  Created by NJL on 2019/9/18.
//  Copyright © 2019 Netease. All rights reserved.
//

#import "NSData+DataToHexString.h"

@implementation NSData (DataToHexString)

-(NSString *)dataToHexString{
    NSUInteger len = [self length];
    char *chars = (char *)[self bytes];
    NSMutableString *hexString = [[NSMutableString alloc]init];
    for (NSUInteger i=0; i<len; i++) {
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx",chars[i]]];
    }
    return hexString;
}

@end

JAVA

/**
	 * DES加密,输入内容将被UTF-8编码后进行加密,密钥长度不要大于8位
	 * 
	 * @param key 密钥
	 * @param content 明文
	 * @return 密文
	 */
	public static String encryptByDES(String key, String content) {
		if ((key == null) || (content == null))
			return null;
 
		// 生成密钥,密钥长度限定为8位,如果超出8位取前8位
		byte[] tmpBytes;
		try {
			tmpBytes = key.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("不支持的字符集。", e);
			return null;
		}
		byte[] keyBytes = new byte[8];
		for (int i = 0; i < tmpBytes.length && i < keyBytes.length; i++) {
			keyBytes[i] = tmpBytes[i];
		}
		// DES加密成为密文
		try {
			Key k = new SecretKeySpec(keyBytes, "DES");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, k);
			byte[] output = cipher.doFinal(content.getBytes("UTF-8"));
			return ConvertUtil.bytesToHexString(output);
		} catch (Exception e) {
			log.error("DES加密失败。", e);
		}
		return null;
	}
 
	/**
	 * DES解密,输入内容是密文,密钥长度不要大于8位
	 * 
	 * @param key 密钥
	 * @param cipherText 密文
	 * @return 明文
	 */
	public static String decryptByDES(String key, String cipherText) {
		if ((key == null) || (cipherText == null))
			return null;
 
		// 生成密钥,密钥长度限定为8位,如果超出8位取前8位
		byte[] tmpBytes;
		try {
			tmpBytes = key.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("不支持的字符集。", e);
			return null;
		}
		byte[] keyBytes = new byte[8];
		for (int i = 0; i < tmpBytes.length && i < keyBytes.length; i++) {
			keyBytes[i] = tmpBytes[i];
		}
		// DES解密成为明文
		try {
			Key k = new SecretKeySpec(keyBytes, "DES");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, k);
			byte[] output = cipher.doFinal(ConvertUtil.hexStringToBytes(cipherText));
			return new String(output, "UTF-8");
		} catch (Exception e) {
			log.error("DES解密失败。", e);
		}
		return null;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值