zoukankan      html  css  js  c++  java
  • 加密解密DES之Android、IOS、C#实现

    Android实现

    package com.sto.express.utils;
    
    
    import java.security.MessageDigest;
    import java.security.spec.AlgorithmParameterSpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    
    /**
     * Des 加密
     *
     * @author qulixuan
     *  2018-1-18 20:42:41
     * Created by Administrator on 2017-09-22.
     */
    
    public class AlgorithmUtil {
        private static final String ALGORITHM = "AES";
        private static final String TSFMN = "DES/CBC/PKCS5Padding";
        private static  AlgorithmParameterSpec iv = null;
    
        public AlgorithmUtil() {
        }
    
    
        //加密
        public static String  encrypt(String message, String key) throws Exception {
            // 加密key
            String firstKey = MD5Utils.digest(key).substring(0, 8).toUpperCase();
            String sha1 = getSha1(firstKey);
            sha1 = sha1.substring(0, 8).toUpperCase();
            byte[] bytes = sha1.getBytes();
    
    
    
            //加密iv
            String temp1 = MD5Utils.digest(key).substring(0, 8).toUpperCase();
            String upperCase = MD5Utils.digest(temp1).toUpperCase().substring(0, 8);
            byte[] bytes2 = upperCase.getBytes("ASCII");
    
           // UnsignedBytes
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    
            DESKeySpec desKeySpec = new DESKeySpec(bytes);
    
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            IvParameterSpec iv = new IvParameterSpec(bytes2);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes1 = cipher.doFinal(message.getBytes("UTF-8"));
            String a = toHexString(bytes1).toUpperCase();
            return a;
        }
    
        // 解密数据
        public static String decrypt(String message, String key) throws Exception {
    
            // 加密key
            String firstKey = MD5Utils.digest(key).substring(0, 8).toUpperCase();
            String sha1 = getSha1(firstKey);
            sha1 = sha1.substring(0, 8).toUpperCase();
            byte[] bytes = sha1.getBytes();
    
    
    
            //加密iv
            String temp1 = MD5Utils.digest(key).substring(0, 8).toUpperCase();
            String upperCase = MD5Utils.digest(temp1).toUpperCase().substring(0, 8);
            byte[] bytes2 = upperCase.getBytes();
    
    
            byte[] bytesrc =convertHexString(message);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            DESKeySpec desKeySpec = new DESKeySpec(bytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            IvParameterSpec iv = new IvParameterSpec(bytes2);
    
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    
            byte[] retByte = cipher.doFinal(bytesrc);
            return new String(retByte,"GBK");
        }
        // int转byte
        public static byte[] intToBytes(int value) {
            byte[] des = new byte[4];
            des[0] = (byte) (value & 0xff);  // 低位(右边)的8个bit位
            des[1] = (byte) ((value >> 8) & 0xff); //第二个8 bit位
            des[2] = (byte) ((value >> 16) & 0xff); //第三个 8 bit位
            /**
             * (byte)((value >> 24) & 0xFF);
             * value向右移动24位, 然后和0xFF也就是(11111111)进行与运算
             * 在内存中生成一个与 value 同类型的值
             * 然后把这个值强制转换成byte类型, 再赋值给一个byte类型的变量 des[3]
             */
            des[3] = (byte) ((value >> 24) & 0xff); //第4个 8 bit位
            return des;
        }
    
    
    
        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;
        }
    
        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();
        }
    
    
        public static String getSha1(String str) {
            if (null == str || 0 == str.length()) {
                return null;
            }
            char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'a', 'b', 'c', 'd', 'e', 'f'};
            try {
                MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
                mdTemp.update(str.getBytes("UTF-8"));
    
                byte[] md = mdTemp.digest();
                int j = md.length;
                char[] buf = new char[j * 2];
                int k = 0;
                for (int i = 0; i < j; i++) {
                    byte byte0 = md[i];
                    buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                    buf[k++] = hexDigits[byte0 & 0xf];
                }
                return new String(buf);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return  null;
        }
    }

     IOS实现

    CocoaSecurity.h

    /*
     CocoaSecurity  1.1
     
     Created by Kelp on 12/5/12.
     Copyright (c) 2012 Kelp http://kelp.phate.org/
     MIT License
     
     CocoaSecurity is core. It provides AES encrypt, AES decrypt, Hash(MD5, HmacMD5, SHA1~SHA512, HmacSHA1~HmacSHA512) messages.
     */
    
    #import <Foundation/Foundation.h>
    #import <Foundation/NSException.h>
    
    
    #pragma mark - CocoaSecurityResult
    @interface CocoaSecurityResult : NSObject
    
    @property (strong, nonatomic, readonly) NSData *data;
    @property (strong, nonatomic, readonly) NSString *utf8String;
    @property (strong, nonatomic, readonly) NSString *hex;
    @property (strong, nonatomic, readonly) NSString *hexLower;
    @property (strong, nonatomic, readonly) NSString *base64;
    
    - (id)initWithBytes:(unsigned char[])initData length:(NSUInteger)length;
    
    @end
    
    
    #pragma mark - CocoaSecurity
    @interface CocoaSecurity : NSObject
    #pragma mark - AES Encrypt
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data key:(NSString *)key;
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data hexKey:(NSString *)key hexIv:(NSString *)iv;
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data key:(NSData *)key iv:(NSData *)iv;
    + (CocoaSecurityResult *)aesEncryptWithData:(NSData *)data key:(NSData *)key iv:(NSData *)iv;
    #pragma mark AES Decrypt
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data key:(NSString *)key;
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data hexKey:(NSString *)key hexIv:(NSString *)iv;
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data key:(NSData *)key iv:(NSData *)iv;
    + (CocoaSecurityResult *)aesDecryptWithData:(NSData *)data key:(NSData *)key iv:(NSData *)iv;
    
    #pragma mark - MD5
    + (CocoaSecurityResult *)md5:(NSString *)hashString;
    + (CocoaSecurityResult *)md5WithData:(NSData *)hashData;
    #pragma mark HMAC-MD5
    + (CocoaSecurityResult *)hmacMd5:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacMd5WithData:(NSData *)hashData hmacKey:(NSString *)key;
    
    #pragma mark - SHA
    + (CocoaSecurityResult *)sha1:(NSString *)hashString;
    + (CocoaSecurityResult *)sha1WithData:(NSData *)hashData;
    + (CocoaSecurityResult *)sha224:(NSString *)hashString;
    + (CocoaSecurityResult *)sha224WithData:(NSData *)hashData;
    + (CocoaSecurityResult *)sha256:(NSString *)hashString;
    + (CocoaSecurityResult *)sha256WithData:(NSData *)hashData;
    + (CocoaSecurityResult *)sha384:(NSString *)hashString;
    + (CocoaSecurityResult *)sha384WithData:(NSData *)hashData;
    + (CocoaSecurityResult *)sha512:(NSString *)hashString;
    + (CocoaSecurityResult *)sha512WithData:(NSData *)hashData;
    #pragma mark HMAC-SHA
    + (CocoaSecurityResult *)hmacSha1:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha1WithData:(NSData *)hashData hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha224:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha224WithData:(NSData *)hashData hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha256:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha256WithData:(NSData *)hashData hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha384:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha384WithData:(NSData *)hashData hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha512:(NSString *)hashString hmacKey:(NSString *)key;
    + (CocoaSecurityResult *)hmacSha512WithData:(NSData *)hashData hmacKey:(NSString *)key;
    @end
    
    
    #pragma mark - CocoaSecurityEncoder
    @interface CocoaSecurityEncoder : NSObject
    - (NSString *)base64:(NSData *)data;
    - (NSString *)hex:(NSData *)data useLower:(BOOL)isOutputLower;
    @end
    
    
    #pragma mark - CocoaSecurityDecoder
    @interface CocoaSecurityDecoder : NSObject
    - (NSData *)base64:(NSString *)data;
    - (NSData *)hex:(NSString *)data;
    @end

    CocoaSecurity.m

    //
    //  CocoaSecurity.m
    //
    //  Created by Kelp on 12/5/12.
    //  Copyright (c) 2012 Kelp http://kelp.phate.org/
    //  MIT License
    //
    
    #import "CocoaSecurity.h"
    #import <CommonCrypto/CommonHMAC.h>
    #import <CommonCrypto/CommonCryptor.h>
    #import "Base64.h"
    
    #pragma mark - CocoaSecurity
    @implementation CocoaSecurity
    
    
    #pragma mark - AES Encrypt
    // default AES Encrypt, key -> SHA384(key).sub(0, 32), iv -> SHA384(key).sub(32, 16)
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data key:(NSString *)key
    {
        CocoaSecurityResult * sha = [self sha384:key];
        NSData *aesKey = [sha.data subdataWithRange:NSMakeRange(0, 32)];
        NSData *aesIv = [sha.data subdataWithRange:NSMakeRange(32, 16)];
        
        return [self aesEncrypt:data key:aesKey iv:aesIv];
    }
    #pragma mark AES Encrypt 128, 192, 256
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data hexKey:(NSString *)key hexIv:(NSString *)iv
    {
        CocoaSecurityDecoder *decoder = [CocoaSecurityDecoder new];
        NSData *aesKey = [decoder hex:key];
        NSData *aesIv = [decoder hex:iv];
        
        return [self aesEncrypt:data key:aesKey iv:aesIv];
    }
    + (CocoaSecurityResult *)aesEncrypt:(NSString *)data key:(NSData *)key iv:(NSData *)iv
    {
        return [self aesEncryptWithData:[data dataUsingEncoding:NSUTF8StringEncoding] key:key iv:iv];
    }
    + (CocoaSecurityResult *)aesEncryptWithData:(NSData *)data key:(NSData *)key iv:(NSData *)iv
    {
        // check length of key and iv
        if ([iv length] != 16) {
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Length of iv is wrong. Length of iv should be 16(128bits)"
                                         userInfo:nil];
        }
        if ([key length] != 16 && [key length] != 24 && [key length] != 32 ) {
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Length of key is wrong. Length of iv should be 16, 24 or 32(128, 192 or 256bits)"
                                         userInfo:nil];
        }
        
        // setup output buffer
        size_t bufferSize = [data length] + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
        
        // do encrypt
        size_t encryptedSize = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                              kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding,
                                              [key bytes],     // Key
                                              [key length],    // kCCKeySizeAES
                                              [iv bytes],       // IV
                                              [data bytes],
                                              [data length],
                                              buffer,
                                              bufferSize,
                                              &encryptedSize);
        if (cryptStatus == kCCSuccess) {
            CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:buffer length:encryptedSize];
            free(buffer);
            
            return result;
        }
        else {
            free(buffer);
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Encrypt Error!"
                                         userInfo:nil];
            return nil;
        }
    }
    #pragma mark - AES Decrypt
    // default AES Decrypt, key -> SHA384(key).sub(0, 32), iv -> SHA384(key).sub(32, 16)
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data key:(NSString *)key
    {
        CocoaSecurityResult * sha = [self sha384:key];
        NSData *aesKey = [sha.data subdataWithRange:NSMakeRange(0, 32)];
        NSData *aesIv = [sha.data subdataWithRange:NSMakeRange(32, 16)];
        
        return [self aesDecryptWithBase64:data key:aesKey iv:aesIv];
    }
    #pragma mark AES Decrypt 128, 192, 256
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data hexKey:(NSString *)key hexIv:(NSString *)iv
    {
        CocoaSecurityDecoder *decoder = [CocoaSecurityDecoder new];
        NSData *aesKey = [decoder hex:key];
        NSData *aesIv = [decoder hex:iv];
        
        return [self aesDecryptWithBase64:data key:aesKey iv:aesIv];
    }
    + (CocoaSecurityResult *)aesDecryptWithBase64:(NSString *)data key:(NSData *)key iv:(NSData *)iv
    {
        CocoaSecurityDecoder *decoder = [CocoaSecurityDecoder new];
        return [self aesDecryptWithData:[decoder base64:data] key:key iv:iv];
    }
    + (CocoaSecurityResult *)aesDecryptWithData:(NSData *)data key:(NSData *)key iv:(NSData *)iv
    {
        // check length of key and iv
        if ([iv length] != 16) {
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Length of iv is wrong. Length of iv should be 16(128bits)"
                                         userInfo:nil];
        }
        if ([key length] != 16 && [key length] != 24 && [key length] != 32 ) {
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Length of key is wrong. Length of iv should be 16, 24 or 32(128, 192 or 256bits)"
                                         userInfo:nil];
        }
        
        // setup output buffer
        size_t bufferSize = [data length] + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
        
        // do encrypt
        size_t encryptedSize = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                              kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding,
                                              [key bytes],     // Key
                                              [key length],    // kCCKeySizeAES
                                              [iv bytes],       // IV
                                              [data bytes],
                                              [data length],
                                              buffer,
                                              bufferSize,
                                              &encryptedSize);
        if (cryptStatus == kCCSuccess) {
            CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:buffer length:encryptedSize];
            free(buffer);
            
            return result;
        }
        else {
            free(buffer);
            @throw [NSException exceptionWithName:@"Cocoa Security"
                                           reason:@"Decrypt Error!"
                                         userInfo:nil];
            return nil;
        }
    }
    
    
    #pragma mark - MD5
    + (CocoaSecurityResult *)md5:(NSString *)hashString
    {
        return [self md5WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)md5WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_MD5_DIGEST_LENGTH);
        
        CC_MD5([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_MD5_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    #pragma mark - HMAC-MD5
    + (CocoaSecurityResult *)hmacMd5:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacMd5WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacMd5WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_MD5_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgMD5, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_MD5_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    
    
    #pragma mark - SHA1
    + (CocoaSecurityResult *)sha1:(NSString *)hashString
    {
        return [self sha1WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)sha1WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_SHA1_DIGEST_LENGTH);
        
        CC_SHA1([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    #pragma mark SHA224
    + (CocoaSecurityResult *)sha224:(NSString *)hashString
    {
        return [self sha224WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)sha224WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_SHA224_DIGEST_LENGTH);
        
        CC_SHA224([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA224_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    #pragma mark SHA256
    + (CocoaSecurityResult *)sha256:(NSString *)hashString
    {
        return [self sha256WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)sha256WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_SHA256_DIGEST_LENGTH);
        
        CC_SHA256([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    #pragma mark SHA384
    + (CocoaSecurityResult *)sha384:(NSString *)hashString
    {
        return [self sha384WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)sha384WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_SHA384_DIGEST_LENGTH);
        
        CC_SHA384([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA384_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    #pragma mark SHA512
    + (CocoaSecurityResult *)sha512:(NSString *)hashString
    {
        return [self sha512WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    + (CocoaSecurityResult *)sha512WithData:(NSData *)hashData
    {
        unsigned char *digest;
        digest = malloc(CC_SHA512_DIGEST_LENGTH);
        
        CC_SHA512([hashData bytes], (CC_LONG)[hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA512_DIGEST_LENGTH];
        free(digest);
        
        return result;
    }
    
    
    #pragma mark - HMAC-SHA1
    + (CocoaSecurityResult *)hmacSha1:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacSha1WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacSha1WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_SHA1_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    #pragma mark HMAC-SHA224
    + (CocoaSecurityResult *)hmacSha224:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacSha224WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacSha224WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_SHA224_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgSHA224, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA224_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    #pragma mark HMAC-SHA256
    + (CocoaSecurityResult *)hmacSha256:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacSha256WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacSha256WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_SHA256_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    #pragma mark HMAC-SHA384
    + (CocoaSecurityResult *)hmacSha384:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacSha384WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacSha384WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_SHA384_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgSHA384, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA384_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    #pragma mark HMAC-SHA512
    + (CocoaSecurityResult *)hmacSha512:(NSString *)hashString hmacKey:(NSString *)key
    {
        return [self hmacSha512WithData:[hashString dataUsingEncoding:NSUTF8StringEncoding] hmacKey:key];
    }
    + (CocoaSecurityResult *)hmacSha512WithData:(NSData *)hashData hmacKey:(NSString *)key
    {
        unsigned char *digest;
        digest = malloc(CC_SHA512_DIGEST_LENGTH);
        const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
        
        CCHmac(kCCHmacAlgSHA512, cKey, strlen(cKey), [hashData bytes], [hashData length], digest);
        CocoaSecurityResult *result = [[CocoaSecurityResult alloc] initWithBytes:digest length:CC_SHA512_DIGEST_LENGTH];
        free(digest);
        cKey = nil;
        
        return result;
    }
    
    @end
    
    
    
    #pragma mark - CocoaSecurityResult
    @implementation CocoaSecurityResult
    
    @synthesize data = _data;
    
    #pragma mark - Init
    - (id)initWithBytes:(unsigned char[])initData length:(NSUInteger)length
    {
        self = [super init];
        if (self) {
            _data = [NSData dataWithBytes:initData length:length];
        }
        return self;
    }
    
    #pragma mark UTF8 String
    // convert CocoaSecurityResult to UTF8 string
    - (NSString *)utf8String
    {
        NSString *result = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
        return result;
    }
    
    #pragma mark HEX
    // convert CocoaSecurityResult to HEX string
    - (NSString *)hex
    {
        CocoaSecurityEncoder *encoder = [CocoaSecurityEncoder new];
        return [encoder hex:_data useLower:false];
    }
    - (NSString *)hexLower
    {
        CocoaSecurityEncoder *encoder = [CocoaSecurityEncoder new];
        return [encoder hex:_data useLower:true];
    }
    
    #pragma mark Base64
    // convert CocoaSecurityResult to Base64 string
    - (NSString *)base64
    {
        CocoaSecurityEncoder *encoder = [CocoaSecurityEncoder new];
        return [encoder base64:_data];
    }
    
    @end
    
    
    #pragma mark - CocoaSecurityEncoder
    @implementation CocoaSecurityEncoder
    
    // convert NSData to Base64
    - (NSString *)base64:(NSData *)data
    {
        return [data base64EncodedString];
    }
    
    // convert NSData to hex string
    - (NSString *)hex:(NSData *)data useLower:(BOOL)isOutputLower
    {
        if (data.length == 0) { return nil; }
        
        static const char HexEncodeCharsLower[] = "0123456789abcdef";
        static const char HexEncodeChars[] = "0123456789ABCDEF";
        char *resultData;
        // malloc result data
        resultData = malloc([data length] * 2 +1);
        // convert imgData(NSData) to char[]
        unsigned char *sourceData = ((unsigned char *)[data bytes]);
        NSUInteger length = [data length];
        
        if (isOutputLower) {
            for (NSUInteger index = 0; index < length; index++) {
                // set result data
                resultData[index * 2] = HexEncodeCharsLower[(sourceData[index] >> 4)];
                resultData[index * 2 + 1] = HexEncodeCharsLower[(sourceData[index] % 0x10)];
            }
        }
        else {
            for (NSUInteger index = 0; index < length; index++) {
                // set result data
                resultData[index * 2] = HexEncodeChars[(sourceData[index] >> 4)];
                resultData[index * 2 + 1] = HexEncodeChars[(sourceData[index] % 0x10)];
            }
        }
        resultData[[data length] * 2] = 0;
        
        // convert result(char[]) to NSString
        NSString *result = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];
        sourceData = nil;
        free(resultData);
        
        return result;
    }
    
    @end
    
    #pragma mark - CocoaSecurityDecoder
    @implementation CocoaSecurityDecoder
    - (NSData *)base64:(NSString *)string
    {
        return [NSData dataWithBase64EncodedString:string];
    }
    - (NSData *)hex:(NSString *)data
    {
        if (data.length == 0) { return nil; }
        
        static const unsigned char HexDecodeChars[] =
        {
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 1, //49
            2, 3, 4, 5, 6, 7, 8, 9, 0, 0, //59
            0, 0, 0, 0, 0, 10, 11, 12, 13, 14,
            15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  //79
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 10, 11, 12,   //99
            13, 14, 15
        };
        
        // convert data(NSString) to CString
        const char *source = [data cStringUsingEncoding:NSUTF8StringEncoding];
        // malloc buffer
        unsigned char *buffer;
        NSUInteger length = strlen(source) / 2;
        buffer = malloc(length);
        for (NSUInteger index = 0; index < length; index++) {
            buffer[index] = (HexDecodeChars[source[index * 2]] << 4) + (HexDecodeChars[source[index * 2 + 1]]);
        }
        // init result NSData
        NSData *result = [NSData dataWithBytes:buffer length:length];
        free(buffer);
        source = nil;
        
        return  result;
    }
    
    @end

     C#实现

            /// <summary>
            /// DES数据解密
            /// 就是出错了,也不能让程序崩溃
            /// </summary>
            /// <param name="targetValue"></param>
            /// <param name="key"></param>
            /// <returns></returns>
            public static string Decrypt(string targetValue, string key = "hairihan")
            {
                if (string.IsNullOrEmpty(targetValue))
                {
                    return string.Empty;
                }
                // 定义DES加密对象
                try
                {
                    var des = new DESCryptoServiceProvider();
                    int len = targetValue.Length / 2;
                    var inputByteArray = new byte[len];
                    int x, i;
                    for (x = 0; x < len; x++)
                    {
                        i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16);
                        inputByteArray[x] = (byte)i;
                    }
                    // 通过两次哈希密码设置对称算法的初始化向量   
                    des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                          (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                                                               Substring(0, 8), "sha1").Substring(0, 8));
                    // 通过两次哈希密码设置算法的机密密钥   
                    des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                         (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
                                                              .Substring(0, 8), "md5").Substring(0, 8));
                    // 定义内存流
                    var ms = new MemoryStream();
                    // 定义加密流
                    var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    return Encoding.Default.GetString(ms.ToArray());
                }
                catch
                {
                }
                return string.Empty;
            }
    
            /// <summary>
            /// DES数据加密
            /// </summary>
            /// <param name="targetValue">目标值</param>
            /// <param name="key">密钥</param>
            /// <returns>加密值</returns>
            public static string Encrypt(string targetValue, string key = "hairihan")
            {
                if (string.IsNullOrEmpty(targetValue))
                {
                    return string.Empty;
                }
    
                var result = new StringBuilder();
                var des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(targetValue);
                // 通过两次哈希密码设置对称算法的初始化向量   
                des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                      (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                                                           Substring(0, 8), "sha1").Substring(0, 8));
                // 通过两次哈希密码设置算法的机密密钥   
                des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                     (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
                                                          .Substring(0, 8), "md5").Substring(0, 8));
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                foreach (byte b in ms.ToArray())
                {
                    result.AppendFormat("{0:X2}", b);
                }
                return result.ToString();
            }

    附带全部源码

    下载

  • 相关阅读:
    httpd服务器的真实ip获取难题
    nginx配置文件详解
    nginx基础知识总结
    Web服务并发I/O模型
    chrony时间服务器
    Linux运维之每日小技巧-检测网站状态以及PV、UV等介绍
    Centos7系统下编写systemd脚本设置redis开机自启动
    Kibana中的Coordinate Map地图报索引错误的问题
    apache的php模块讲解以及搭建phpmyadmin管理数据库mysql
    AMP架构补充与wordpress部署
  • 原文地址:https://www.cnblogs.com/hnsongbiao/p/8629971.html
Copyright © 2011-2022 走看看