欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-14 13:16:28
...

以下代码有添加用到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;
	}

上一篇: [NCTF2019]SQLi

下一篇: [NCTF2019]SQLi