码迷,mamicode.com
首页 > 编程语言 > 详细

PHP、JAVA、C#、Object-C 通用的DES加密

时间:2015-07-30 20:59:38      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

php:

技术分享
 1 class JoDES {
 2  
 3     private static $_instance = NULL;
 4     /**
 5      * @return JoDES
 6      */
 7     public static function share() {
 8         if (is_null(self::$_instance)) {
 9             self::$_instance = new JoDES();
10         }
11         return self::$_instance;
12     }
13  
14     /**
15      * 加密
16      * @param string $str 要处理的字符串
17      * @param string $key 加密Key,为8个字节长度
18      * @return string
19      */
20     public function encode($str, $key) {
21         $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
22         $str = $this->pkcs5Pad($str, $size);
23         $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
24         $ret = base64_encode($aaa);
25         return $ret;
26     }
27  
28     /**
29      * 解密
30      * @param string $str 要处理的字符串
31      * @param string $key 解密Key,为8个字节长度
32      * @return string
33      */
34     public function decode($str, $key) {
35         $strBin = base64_decode($str);
36         $str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key);
37         $str = $this->pkcs5Unpad($str);
38         return $str;
39     }
40  
41     function hex2bin($hexData) {
42         $binData = "";
43         for ($i = 0; $i < strlen($hexData); $i += 2) {
44             $binData .= chr(hexdec(substr($hexData, $i, 2)));
45         }
46         return $binData;
47     }
48  
49     function pkcs5Pad($text, $blocksize) {
50         $pad = $blocksize - (strlen($text) % $blocksize);
51         return $text . str_repeat(chr($pad), $pad);
52     }
53  
54     function pkcs5Unpad($text) {
55         $pad = ord($text {strlen($text) - 1});
56         if ($pad > strlen($text))
57             return false;
58  
59         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
60             return false;
61  
62         return substr($text, 0, - 1 * $pad);
63     }
64  
65 }
View Code

 

c#:

技术分享
 1 public class MyDes
 2     {
 3         /// <summary>
 4         /// DES加密方法
 5         /// </summary>
 6         /// <param name="strPlain">明文</param>
 7         /// <param name="strDESKey">密钥</param>
 8         /// <param name="strDESIV">向量</param>
 9         /// <returns>密文</returns>
10         public static string Encode(string source, string _DESKey)
11         {
12             StringBuilder sb = new StringBuilder();
13             using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
14             {
15                 byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey);
16                 byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey);
17                 byte[] dataByteArray = Encoding.UTF8.GetBytes(source);
18                 des.Mode = System.Security.Cryptography.CipherMode.CBC;
19                 des.Key = key;
20                 des.IV = iv;
21                 string encrypt = "";
22                 using (MemoryStream ms = new MemoryStream())
23                 using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
24                 {
25                     cs.Write(dataByteArray, 0, dataByteArray.Length);
26                     cs.FlushFinalBlock();
27                     encrypt = Convert.ToBase64String(ms.ToArray());
28                 }
29                 return encrypt;
30             }
31         }
32  
33         /// <summary>
34         /// 进行DES解密。
35         /// </summary>
36         /// <param name="pToDecrypt">要解密的base64串</param>
37         /// <param name="sKey">密钥,且必须为8位。</param>
38         /// <returns>已解密的字符串。</returns>
39         public static string Decode(string source, string sKey)
40         {
41             byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source);
42             using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
43             {
44                 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
45                 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
46                 System.IO.MemoryStream ms = new System.IO.MemoryStream();
47                 using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
48                 {
49                     cs.Write(inputByteArray, 0, inputByteArray.Length);
50                     cs.FlushFinalBlock();
51                     cs.Close();
52                 }
53                 string str = Encoding.UTF8.GetString(ms.ToArray());
54                 ms.Close();
55                 return str;
56             }
57         }
58     }
View Code

 

Object-c:

技术分享
  1 /***  JoDes.h ***/
  2  
  3 #import <Foundation/Foundation.h>
  4 #import <CommonCrypto/CommonDigest.h>
  5 #import <CommonCrypto/CommonCryptor.h>
  6  
  7 @interface JoDes : NSObject
  8  
  9 + (NSString *) encode:(NSString *)str key:(NSString *)key;
 10 + (NSString *) decode:(NSString *)str key:(NSString *)key;
 11  
 12 @end
 13  
 14  
 15 /***  JoDes.m ***/
 16 //
 17 //  XLEncrytHelper.m
 18 //  NewHoldGold
 19 //
 20 //  Created by 梁鑫磊 on 13-12-27.
 21 //  Copyright (c) 2013年 zsgjs. All rights reserved.
 22 //
 23  
 24 #import "JoDes.h"
 25  
 26 @interface JoDes()
 27  
 28 + (NSString *) encodeBase64WithString:(NSString *)strData;
 29 + (NSString *) encodeBase64WithData:(NSData *)objData;
 30 + (NSData *) decodeBase64WithString:(NSString *)strBase64;
 31  
 32 + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
 33                   context:(CCOperation)encryptOrDecrypt;
 34  
 35 @end
 36  
 37 @implementation JoDes
 38  
 39 + (NSString *) encode:(NSString *)str key:(NSString *)key
 40 {
 41     // doCipher 不能编汉字,所以要进行 url encode
 42     NSMutableString* str1 = [JoDes urlEncode:str];
 43     NSMutableString* encode = [NSMutableString stringWithString:[JoDes doCipher:str1 key:key context:kCCEncrypt]];
 44     [JoDes formatSpecialCharacters:encode];
 45     return encode;
 46 }
 47  
 48 + (NSString *) decode:(NSString *)str key:(NSString *)key
 49 {
 50     NSMutableString *str1 = [NSMutableString stringWithString:str];
 51     [JoDes reformatSpecialCharacters:str1];
 52     NSString *rt = [JoDes doCipher:str1 key:key context:kCCDecrypt];
 53     return rt;
 54 }
 55  
 56 + (NSMutableString *)urlEncode:(NSString*)str
 57 {
 58     NSMutableString* encodeStr = [NSMutableString stringWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
 59     [encodeStr replaceOccurrencesOfString:@"+" withString:@"%2B" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
 60     [encodeStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
 61     return encodeStr;
 62 }
 63  
 64 + (void)formatSpecialCharacters:(NSMutableString *)str
 65 {
 66     [str replaceOccurrencesOfString:@"+" withString:@"$$" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
 67     [str replaceOccurrencesOfString:@"/" withString:@"@@" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
 68 }
 69  
 70  
 71 + (void)reformatSpecialCharacters:(NSMutableString *)str
 72 {
 73     [str replaceOccurrencesOfString:@"$$" withString:@"+" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
 74     [str replaceOccurrencesOfString:@"@@" withString:@"/" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])];
 75 }
 76  
 77 + (NSString *)encodeBase64WithString:(NSString *)strData {
 78     return [JoDes encodeBase64WithData:[strData dataUsingEncoding:NSUTF8StringEncoding]];
 79 }
 80  
 81  
 82 + (NSString *)encodeBase64WithData:(NSData *)objData {
 83     NSString *encoding = nil;
 84     unsigned char *encodingBytes = NULL;
 85     @try {
 86         static char encodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 87         static NSUInteger paddingTable[] = {0,2,1};
 88          
 89         NSUInteger dataLength = [objData length];
 90         NSUInteger encodedBlocks = (dataLength * 8) / 24;
 91         NSUInteger padding = paddingTable[dataLength % 3];
 92         if( padding > 0 ) encodedBlocks++;
 93         NSUInteger encodedLength = encodedBlocks * 4;
 94          
 95         encodingBytes = malloc(encodedLength);
 96         if( encodingBytes != NULL ) {
 97             NSUInteger rawBytesToProcess = dataLength;
 98             NSUInteger rawBaseIndex = 0;
 99             NSUInteger encodingBaseIndex = 0;
100             unsigned char *rawBytes = (unsigned char *)[objData bytes];
101             unsigned char rawByte1, rawByte2, rawByte3;
102             while( rawBytesToProcess >= 3 ) {
103                 rawByte1 = rawBytes[rawBaseIndex];
104                 rawByte2 = rawBytes[rawBaseIndex+1];
105                 rawByte3 = rawBytes[rawBaseIndex+2];
106                 encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
107                 encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
108                 encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) | ((rawByte3 >> 6) & 0x03) ];
109                 encodingBytes[encodingBaseIndex+3] = encodingTable[(rawByte3 & 0x3F)];
110                  
111                 rawBaseIndex += 3;
112                 encodingBaseIndex += 4;
113                 rawBytesToProcess -= 3;
114             }
115             rawByte2 = 0;
116             switch (dataLength-rawBaseIndex) {
117                 case 2:
118                     rawByte2 = rawBytes[rawBaseIndex+1];
119                 case 1:
120                     rawByte1 = rawBytes[rawBaseIndex];
121                     encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
122                     encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
123                     encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) ];
124                     // we can skip rawByte3 since we have a partial block it would always be 0
125                     break;
126             }
127             // compute location from where to begin inserting padding, it may overwrite some bytes from the partial block encoding
128             // if their value was 0 (cases 1-2).
129             encodingBaseIndex = encodedLength - padding;
130             while( padding-- > 0 ) {
131                 encodingBytes[encodingBaseIndex++] = =;
132             }
133             encoding = [[NSString alloc] initWithBytes:encodingBytes length:encodedLength encoding:NSASCIIStringEncoding];
134         }
135     }
136     @catch (NSException *exception) {
137         encoding = nil;
138         NSLog(@"WARNING: error occured while tring to encode base 32 data: %@", exception);
139     }
140     @finally {
141         if( encodingBytes != NULL ) {
142             free( encodingBytes );
143         }
144     }
145     return encoding;
146      
147 }
148  
149 + (NSData *)decodeBase64WithString:(NSString *)strBase64 {
150     NSData *data = nil;
151     unsigned char *decodedBytes = NULL;
152     @try {
153 #define __ 255
154         static char decodingTable[256] = {
155             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x00 - 0x0F
156             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x10 - 0x1F
157             __,__,__,__, __,__,__,__, __,__,__,62, __,__,__,63,  // 0x20 - 0x2F
158             52,53,54,55, 56,57,58,59, 60,61,__,__, __, 0,__,__,  // 0x30 - 0x3F
159             __, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,  // 0x40 - 0x4F
160             15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__,  // 0x50 - 0x5F
161             __,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,  // 0x60 - 0x6F
162             41,42,43,44, 45,46,47,48, 49,50,51,__, __,__,__,__,  // 0x70 - 0x7F
163             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x80 - 0x8F
164             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x90 - 0x9F
165             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xA0 - 0xAF
166             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xB0 - 0xBF
167             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xC0 - 0xCF
168             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xD0 - 0xDF
169             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xE0 - 0xEF
170             __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xF0 - 0xFF
171         };
172         strBase64 = [strBase64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
173         NSData *encodedData = [strBase64 dataUsingEncoding:NSASCIIStringEncoding];
174         unsigned char *encodedBytes = (unsigned char *)[encodedData bytes];
175          
176         NSUInteger encodedLength = [encodedData length];
177         NSUInteger encodedBlocks = (encodedLength+3) >> 2;
178         NSUInteger expectedDataLength = encodedBlocks * 3;
179          
180         unsigned char decodingBlock[4];
181          
182         decodedBytes = malloc(expectedDataLength);
183         if( decodedBytes != NULL ) {
184              
185             NSUInteger i = 0;
186             NSUInteger j = 0;
187             NSUInteger k = 0;
188             unsigned char c;
189             while( i < encodedLength ) {
190                 c = decodingTable[encodedBytes[i]];
191                 i++;
192                 if( c != __ ) {
193                     decodingBlock[j] = c;
194                     j++;
195                     if( j == 4 ) {
196                         decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
197                         decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
198                         decodedBytes[k+2] = (decodingBlock[2] << 6) | (decodingBlock[3]);
199                         j = 0;
200                         k += 3;
201                     }
202                 }
203             }
204              
205             // Process left over bytes, if any
206             if( j == 3 ) {
207                 decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
208                 decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
209                 k += 2;
210             } else if( j == 2 ) {
211                 decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
212                 k += 1;
213             }
214             data = [[NSData alloc] initWithBytes:decodedBytes length:k];
215         }
216     }
217     @catch (NSException *exception) {
218         data = nil;
219         NSLog(@"WARNING: error occured while decoding base 32 string: %@", exception);
220     }
221     @finally {
222         if( decodedBytes != NULL ) {
223             free( decodedBytes );
224         }
225     }
226     return data;
227      
228 }
229  
230  
231 + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
232                   context:(CCOperation)encryptOrDecrypt {
233     NSStringEncoding EnC = NSUTF8StringEncoding;
234      
235     NSMutableData *dTextIn;
236     if (encryptOrDecrypt == kCCDecrypt) {
237         dTextIn = [[JoDes decodeBase64WithString:sTextIn] mutableCopy];
238     }
239     else{
240         dTextIn = [[sTextIn dataUsingEncoding: EnC] mutableCopy];
241     }
242     NSMutableData * dKey = [[sKey dataUsingEncoding:EnC] mutableCopy];
243     [dKey setLength:kCCBlockSizeDES];
244     uint8_t *bufferPtr1 = NULL;
245     size_t bufferPtrSize1 = 0;
246     size_t movedBytes1 = 0;
247     //uint8_t iv[kCCBlockSizeDES];
248     //memset((void *) iv, 0x0, (size_t) sizeof(iv));
249     //    Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
250     bufferPtrSize1 = ([sTextIn length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
251     bufferPtr1 = malloc(bufferPtrSize1 * sizeof(uint8_t));
252     memset((void *)bufferPtr1, 0x00, bufferPtrSize1);
253      
254     CCCrypt(encryptOrDecrypt, // CCOperation op
255             kCCAlgorithmDES, // CCAlgorithm alg
256             kCCOptionPKCS7Padding, // CCOptions options
257             [dKey bytes], // const void *key
258             [dKey length], // size_t keyLength //
259             [dKey bytes], // const void *iv
260             [dTextIn bytes], // const void *dataIn
261             [dTextIn length],  // size_t dataInLength
262             (void *)bufferPtr1, // void *dataOut
263             bufferPtrSize1,     // size_t dataOutAvailable
264             &movedBytes1);
265      
266     //[dTextIn release];
267     //[dKey release];
268      
269     NSString * sResult;
270     if (encryptOrDecrypt == kCCDecrypt){
271         sResult = [[NSString alloc] initWithData:[NSData dataWithBytes:bufferPtr1 length:movedBytes1] encoding:EnC];
272         free(bufferPtr1);
273     }
274     else {
275         NSData *dResult = [NSData dataWithBytes:bufferPtr1 length:movedBytes1];
276         free(bufferPtr1);
277         sResult = [JoDes encodeBase64WithData:dResult];
278     }
279     return sResult;
280 }
281  
282  
283  
284 @end
View Code

 

java:

技术分享
 1 package com.example.aric.test;
 2  
 3 import javax.crypto.Cipher;
 4 import javax.crypto.SecretKey;
 5 import javax.crypto.SecretKeyFactory;
 6 import javax.crypto.spec.DESKeySpec;
 7 import javax.crypto.spec.IvParameterSpec;
 8  
 9 import android.util.Base64;
10  
11 public class DES {
12  
13     public final static String DES_KEY_STRING = "ABSujsuu";
14      
15     public static String encrypt(String message, String key) throws Exception {
16         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
17  
18         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
19  
20         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
21         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
22         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
23         cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
24  
25         return encodeBase64(cipher.doFinal(message.getBytes("UTF-8")));
26     }
27  
28     public static String decrypt(String message, String key) throws Exception {
29  
30         byte[] bytesrc = decodeBase64(message);//convertHexString(message);
31         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
32         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
33         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
34         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
35         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
36  
37         cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
38  
39         byte[] retByte = cipher.doFinal(bytesrc);
40         return new String(retByte);
41     }
42  
43     public static byte[] convertHexString(String ss) {
44         byte digest[] = new byte[ss.length() / 2];
45         for (int i = 0; i < digest.length; i++) {
46             String byteString = ss.substring(2 * i, 2 * i + 2);
47             int byteValue = Integer.parseInt(byteString, 16);
48             digest[i] = (byte) byteValue;
49         }
50  
51         return digest;
52     }
53  
54     public static String toHexString(byte b[]) {
55         StringBuffer hexString = new StringBuffer();
56         for (int i = 0; i < b.length; i++) {
57             String plainText = Integer.toHexString(0xff & b[i]);
58             if (plainText.length() < 2)
59                 plainText = "0" + plainText;
60             hexString.append(plainText);
61         }
62  
63         return hexString.toString();
64     }
65  
66      
67     public static String encodeBase64(byte[] b) {
68         return Base64.encodeToString(b, Base64.DEFAULT);
69     }
70      
71     public static byte[] decodeBase64(String base64String) {
72         return Base64.decode(base64String, Base64.DEFAULT);
73     }
74 }
View Code

 

PHP、JAVA、C#、Object-C 通用的DES加密

标签:

原文地址:http://www.cnblogs.com/xiaoliu66007/p/4690310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!