加密解密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(, )];
NSData *aesIv = [sha.data subdataWithRange:NSMakeRange(, )]; 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] != ) {
@throw [NSException exceptionWithName:@"Cocoa Security"
reason:@"Length of iv is wrong. Length of iv should be 16(128bits)"
userInfo:nil];
}
if ([key length] != && [key length] != && [key length] != ) {
@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 = ;
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(, )];
NSData *aesIv = [sha.data subdataWithRange:NSMakeRange(, )]; 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] != ) {
@throw [NSException exceptionWithName:@"Cocoa Security"
reason:@"Length of iv is wrong. Length of iv should be 16(128bits)"
userInfo:nil];
}
if ([key length] != && [key length] != && [key length] != ) {
@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 = ;
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 == ) { return nil; } static const char HexEncodeCharsLower[] = "0123456789abcdef";
static const char HexEncodeChars[] = "0123456789ABCDEF";
char *resultData;
// malloc result data
resultData = malloc([data length] * +);
// convert imgData(NSData) to char[]
unsigned char *sourceData = ((unsigned char *)[data bytes]);
NSUInteger length = [data length]; if (isOutputLower) {
for (NSUInteger index = ; index < length; index++) {
// set result data
resultData[index * ] = HexEncodeCharsLower[(sourceData[index] >> )];
resultData[index * + ] = HexEncodeCharsLower[(sourceData[index] % 0x10)];
}
}
else {
for (NSUInteger index = ; index < length; index++) {
// set result data
resultData[index * ] = HexEncodeChars[(sourceData[index] >> )];
resultData[index * + ] = HexEncodeChars[(sourceData[index] % 0x10)];
}
}
resultData[[data length] * ] = ; // 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 == ) { return nil; } static const unsigned char HexDecodeChars[] =
{
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , , //
, , , , , , , , , , //
, , , , , , , , , ,
, , , , , , , , , , //
, , , , , , , , , ,
, , , , , , , , , , //
, ,
}; // convert data(NSString) to CString
const char *source = [data cStringUsingEncoding:NSUTF8StringEncoding];
// malloc buffer
unsigned char *buffer;
NSUInteger length = strlen(source) / ;
buffer = malloc(length);
for (NSUInteger index = ; index < length; index++) {
buffer[index] = (HexDecodeChars[source[index * ]] << ) + (HexDecodeChars[source[index * + ]]);
}
// 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 / ;
var inputByteArray = new byte[len];
int x, i;
for (x = ; x < len; x++)
{
i = Convert.ToInt32(targetValue.Substring(x * , ), );
inputByteArray[x] = (byte)i;
}
// 通过两次哈希密码设置对称算法的初始化向量
des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
Substring(, ), "sha1").Substring(, ));
// 通过两次哈希密码设置算法的机密密钥
des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
.Substring(, ), "md5").Substring(, ));
// 定义内存流
var ms = new MemoryStream();
// 定义加密流
var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , 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(, ), "sha1").Substring(, ));
// 通过两次哈希密码设置算法的机密密钥
des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
.Substring(, ), "md5").Substring(, ));
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
foreach (byte b in ms.ToArray())
{
result.AppendFormat("{0:X2}", b);
}
return result.ToString();
}
附带全部源码
加密解密DES之Android、IOS、C#实现的更多相关文章
- C#加密解密(DES,AES,Base64,md5,SHA256,RSA,RC4)
一:异或^简单加解密(数字类型) 1:原理: 异或用于比较两个二进制数的相应位,在执行按位"异或"运算时,如果两个二进制数的相应位都为1或者都为0,则返回0;如果两个二进制数的相应 ...
- C#与Java同步加密解密DES算法
在实际项目中,往往前端和后端使用不同的语言.比如使用C#开发客户端,使用Java开发服务器端.有时出于安全性考虑需要将字符加密传输后,由服务器解密获取.本文介绍一种采用DES算法的C#与Java同步加 ...
- C#加密解密DES字符串<转>
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptograph ...
- JAVA加密解密DES对称加密算法
下面用DES对称加密算法(设定一个密钥,然后对所有的数据进行加密)来简单举个例子. 首先,生成一个密钥KEY. 我把它保存到key.txt中.这个文件就象是一把钥匙.谁拥有它,谁就能解开我们的类文件. ...
- ◆JAVA加密解密-DES
DES算法提供CBC, OFB, CFB, ECB四种模式,MAC是基于ECB实现的. 一.数据补位 DES数据加解密就是将数据按照8个字节一段进行DES加密或解密得到一段8个字节的密文或者明文,最后 ...
- Java加密解密相关
关于解释加密解密中的填充方案: http://laokaddk.blog.51cto.com/368606/461279/ 关于对称加密中的反馈模式: http://blog.csdn.net/aaa ...
- ASP.NET常用技术之加密解密
在开发项目中有许多数据需要我们进行加密解密操作,这里介绍几个加密解密的方法. 一:MD5加密 MD5加密是一种单向的加密算法,它只能加密,加密后不能进行逆向解密操作,常用于数字签名和加密用户密码. 下 ...
- C#/IOS/Android通用加密解密方法
原文:C#/IOS/Android通用加密解密方法 公司在做移动端ios/android,服务器提供接口使用的.net,用到加密解密这一块,也在网上找了一些方法,有些是.net加密了android解密 ...
- .NET/android/java/iOS AES通用加密解密(修正安卓)
移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道.为了让数据交互更安全,我们需要对数据进行加密传输.今天研究了一下,把几种语言的加密都 ...
随机推荐
- Linux基础学习笔记3-用户权限
本章内容 用户user 令牌token,identity Linux用户:Uername/UID 管理员:root,0 普通用户:1-65535 系统用户:1-499,1-999(Centos7) 对 ...
- python学习笔记(5)-time库的使用
import time 一.时间获取函数 time(), ctime(),gmtime() >>> import time >>> time.time() 1524 ...
- list类型功能剖析
append 向后追加 name_list=["eirc","alex","tony"] name_list.append('seven' ...
- WPF TextBox控件中文字实现垂直居中
TextBox纵向长度比较长但文字字体比较小的时候,在输入时就会发现文字不是垂直居中的. 而使用中我们发现,TextBox虽然可以设置文字的水平对齐方式,但却没有相应的属性让我们来调节他的垂直对齐方式 ...
- java开发支付宝支付详细流程_demo的运行
首先我要吐槽一下支付宝的开放平台简直就是一个迷宫,赞同的顶一下,下面我把要下载的地址给贴出来要不真不好找: 一.准备工作 1.签名工具下载 https://docs.open.alipay.com/2 ...
- Multi-Targeting and Porting a .NET Library to .NET Core 2.0
Creating a new .NET Standard Project The first step for moving this library is to create a new .NET ...
- c++ 的绝对值函数
添加头文件 #include <cmath> 对于整数 abs(); 对于浮点数 fabs();
- hdu-3374(kmp+最小表示法)
题意:给你一个字符串,这个字符串我们可以把把他变成n个字符串按照以下规则:将当前字符串第一个放到字符串最后一位,字符串的下标依次向前推一位,比如:s[1] s[2 ]s[3] s[4]->s[2 ...
- python基础数据类型--list列表
列表: 列表是python中的基础数据类型之一,其他语言中也有类似于列表的数据类型,比如js中叫数组,他是以[]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型比如: li = [‘alex ...
- python字典与集合操作
字典操作 字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划.字母来查对应页的详细内容. 语法: info = { 's1': "jack", 's3' ...