PHP、JAVA、IOS(OC)实现DES(DES/CBC/PKCS5Padding)加解密

1.PHP[DesCryptUtil2.php]

<?php
/**
 * Created by PhpStorm.
 * User: Alvin Tang
 * Date: 2017/6/2
 * Time: 10:03
 * Author: 442353346@qq.com
 * Desc: 16进制DES加密和解密
 */

class DesCryptUtil2{
    //密钥8位
    public $key = '|$|@d!@&';

    /**
     * 构造函数
     * DesCryptUtil2 constructor.
     * @param string $key
     */

    function __construct($key = ''){
        $this->key = empty($key) ? $this->key : $key;
    }

    /**
     * @desc 加密返回十六进制字符串
     * @param string $str
     * @return string
     */

    public function encrypt($str) {
        $size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC);
        $str = $this->pkcs5Pad($str, $size);
        return strtolower(bin2hex( mcrypt_encrypt(MCRYPT_DES, $this->key, $str, MCRYPT_MODE_CBC, $this->key)));
    }

    /**
     * @desc 解密
     * @param string $str
     * @return string
     */

    public function decrypt($str) {
        $strBin = $this->hex2bin(strtolower($str));
        $str = mcrypt_decrypt(MCRYPT_DES, $this->key, $strBin, MCRYPT_MODE_CBC, $this->key);
        $str = $this->pkcs5Unpad($str);
        return $str;
    }

    /**
     * @param $hexData
     * @return string
     */

    public function hex2bin($hexData) {
        $binData = '';
        for($i = 0; $i < strlen ($hexData ); $i += 2) {
            $binData .= chr(hexdec(substr($hexData, $i, 2)));
        }
        return $binData;
    }

    /**
     * @param $text
     * @param $blocksize
     * @return string
     */

    public function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    /**
     * @param $text
     * @return bool|string
     */

    public function pkcs5Unpad($text) {
        $pad = ord ($text{strlen($text) - 1});
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr($text, 0, -1 * $pad);
    }
}

 

2.JAVA[DES.java]

package me.daei.soundmeter;

/**
 * Created by Administrator on 2017/6/2.
 */


import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKey;

import android.util.Base64;

public class DES {
    /**
     * DES 加密
     * @param message
     * @param key
     * @return
     * @throws Exception
     */

    public static String encrypt(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);

        //return encodeBase64(cipher.doFinal(message.getBytes("UTF-8")));
        return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
    }

    /**
     * DES解密
     * @param message
     * @param key
     * @return
     * @throws Exception
     */

    public static String decrypt(String message, String key) throws Exception {

        //byte[] bytesrc = decodeBase64(message);
        byte[] bytesrc = convertHexString(message);
        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);
    }

    /**
     * 16进制字符串转为为字节数组
     * @param ss
     * @return
     */

    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }

        return digest;
    }

    /**
     * 转化为16进制字符串
     * @param b
     * @return
     */

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }

        return hexString.toString();
    }

    /**
     * BASE64编码
     * @param b
     * @return
     */

    public static String encodeBase64(byte[] b) {
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    /**
     * BASE64解码
     * @param base64String
     * @return
     */

    public static byte[] decodeBase64(String base64String) {
        return Base64.decode(base64String, Base64.DEFAULT);
    }

}

3.IOS[Object-C]

//
//  ViewController.m
//  testObjectC
//
//  Created by TangPing on 2017/12/22.
//  Copyright © 2017年 TangPing. All rights reserved.
//

#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

//如果需要base64请加载头文件
//#import "Base64.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    NSString* key = @"|$%@d!@y";
    NSString* test = @"123456";
   
    NSString* result = [self encryptUseDES:test key:key];
   
    NSLog(@"%@", result);
}

//与下面的加密并未实现同步,如果有需要可自行实现十六进制转Byte算法

/*
- (NSString*) decryptUseDES:(NSString*)cipherText key:(NSString*)key {
    // 利用 GTMBase64 解碼 Base64 字串
   
    NSData* cipherData = [cipherText base64DecodedData];//如果想与加密同步,请自行实现十六进制转Byte算法
    unsigned char buffer[1024];  //注意空间大小
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
   
    // IV 偏移量不需使用
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,//kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          [key UTF8String],//nil,
                                          [cipherData bytes],
                                          [cipherData length],
                                          buffer,
                                          1024,  //注意空间大小
                                          &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return plainText;
}
*/


- (NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
{
    NSInteger bufferSize = 1024;
    NSData *data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    unsigned char buffer[bufferSize];  //注意空间大小
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
   
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,//kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          [key UTF8String],//nil,
                                          [data bytes],
                                          [data length],
                                          buffer,
                                          bufferSize,  //注意空间大小
                                          &numBytesEncrypted);
   
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData *dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
       
        //转化为byte
        Byte *byte = (Byte *)[dataTemp bytes];
       
        NSUInteger len = [dataTemp length];
       
        plainText = [self toHexString:byte size:len];
       
        //plainText = [dataTemp base64EncodedString];
       
    }else{
        //NSLog(@"DES加密失败");
    }
    return plainText;
}

- (NSString *) toHexString:(Byte*)byte size:(NSInteger)size {
    NSMutableArray* tempArray = [NSMutableArray arrayWithCapacity:size];
   
    for(int i =0;i<size;i++){
        NSString* newHexStr = [NSString stringWithFormat:@"%x",byte[i]&0xff];
        if(newHexStr.length < 2){
            newHexStr = [@"0" stringByAppendingString:newHexStr];
        }
        [tempArray addObject:newHexStr];
    }
   
    return [tempArray componentsJoinedByString:@""];
}

@end

Base64.h

//
//  Base64.h
//  testObjectC
//
//  Created by TangPing on 2018/1/5.
//  Copyright © 2018年 TangPing. All rights reserved.
//

#ifndef Base64_h
#define Base64_h


#endif /* Base64_h */

#import <Foundation/Foundation.h>


@interface NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
- (NSString *)base64EncodedString;

@end


@interface NSString (Base64)

+ (NSString *)stringWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
- (NSString *)base64EncodedString;
- (NSString *)base64DecodedString;
- (NSData *)base64DecodedData;

@end

Base64.m

#import "Base64.h"


#pragma GCC diagnostic ignored "-Wselector"


#import <Availability.h>
#if !__has_feature(objc_arc)
#error This library requires automatic reference counting
#endif


@implementation NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (![string length]) return nil;
   
    NSData *decoded = nil;
   
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
   
    if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])
    {
        decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];
    }
    else
       
#endif
       
    {
        decoded = [[self alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    }
   
    return [decoded length]? decoded: nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    if (![self length]) return nil;
   
    NSString *encoded = nil;
   
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
   
    if (![NSData instancesRespondToSelector:@selector(base64EncodedStringWithOptions:)])
    {
        //encoded = [self base64Encoding];
        encoded = [self base64EncodedString];
    }
    else
       
#endif
       
    {
        switch (wrapWidth)
        {
            case 64:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            }
            case 76:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
            }
            default:
            {
                encoded = [self base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
            }
        }
    }
   
    if (!wrapWidth || wrapWidth >= [encoded length])
    {
        return encoded;
    }
   
    wrapWidth = (wrapWidth / 4) * 4;
    NSMutableString *result = [NSMutableString string];
    for (NSUInteger i = 0; i < [encoded length]; i+= wrapWidth)
    {
        if (i + wrapWidth >= [encoded length])
        {
            [result appendString:[encoded substringFromIndex:i]];
            break;
        }
        [result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];
        [result appendString:@"\r\n"];
    }
   
    return result;
}

- (NSString *)base64EncodedString
{
    return [self base64EncodedStringWithWrapWidth:0];
}

@end


@implementation NSString (Base64)

+ (NSString *)stringWithBase64EncodedString:(NSString *)string
{
    NSData *data = [NSData dataWithBase64EncodedString:string];
    if (data)
    {
        return [[self alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedStringWithWrapWidth:wrapWidth];
}

- (NSString *)base64EncodedString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedString];
}

- (NSString *)base64DecodedString
{
    return [NSString stringWithBase64EncodedString:self];
}

- (NSData *)base64DecodedData
{
    return [NSData dataWithBase64EncodedString:self];
}

@end

Leave a Comment