JAVA、Android:
package com.example.aric.test; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import android.util.Base64; public class DES { public final static String DES_KEY_STRING = "ABSujsuu"; 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"))); } public static String decrypt(String message, String key) throws Exception { byte[] bytesrc = decodeBase64(message);//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); } 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 encodeBase64(byte[] b) { return Base64.encodeToString(b, Base64.DEFAULT); } public static byte[] decodeBase64(String base64String) { return Base64.decode(base64String, Base64.DEFAULT); } }
PHP:
class JoDES { private static $_instance = NULL; /** * @return JoDES */ public static function share() { if (is_null(self::$_instance)) { self::$_instance = new JoDES(); } return self::$_instance; } /** * 加密 * @param string $str 要处理的字符串 * @param string $key 加密Key,为8个字节长度 * @return string */ public function encode($str, $key) { $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC); $str = $this->pkcs5Pad($str, $size); $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key); $ret = base64_encode($aaa); return $ret; } /** * 解密 * @param string $str 要处理的字符串 * @param string $key 解密Key,为8个字节长度 * @return string */ public function decode($str, $key) { $strBin = base64_decode($str); $str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key); $str = $this->pkcs5Unpad($str); return $str; } function hex2bin($hexData) { $binData = ""; for ($i = 0; $i < strlen($hexData); $i += 2) { $binData .= chr(hexdec(substr($hexData, $i, 2))); } return $binData; } function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } 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); } }
C#:
public class MyDes { /// <summary> /// DES加密方法 /// </summary> /// <param name="strPlain">明文</param> /// <param name="strDESKey">密钥</param> /// <param name="strDESIV">向量</param> /// <returns>密文</returns> public static string Encode(string source, string _DESKey) { StringBuilder sb = new StringBuilder(); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey); byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey); byte[] dataByteArray = Encoding.UTF8.GetBytes(source); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.Key = key; des.IV = iv; string encrypt = ""; using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(dataByteArray, 0, dataByteArray.Length); cs.FlushFinalBlock(); encrypt = Convert.ToBase64String(ms.ToArray()); } return encrypt; } } /// <summary> /// 进行DES解密。 /// </summary> /// <param name="pToDecrypt">要解密的base64串</param> /// <param name="sKey">密钥,且必须为8位。</param> /// <returns>已解密的字符串。</returns> public static string Decode(string source, string sKey) { byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } }
Object-C:
/*** JoDes.h ***/ #import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonCryptor.h> @interface JoDes : NSObject + (NSString *) encode:(NSString *)str key:(NSString *)key; + (NSString *) decode:(NSString *)str key:(NSString *)key; @end /*** JoDes.m ***/ // XLEncrytHelper.m // NewHoldGold // Created by Mr.Liao on 2016-01-22. // Copyright (c) 2016年 Nomanland. All rights reserved. #import "JoDes.h" @interface JoDes() + (NSString *) encodeBase64WithString:(NSString *)strData; + (NSString *) encodeBase64WithData:(NSData *)objData; + (NSData *) decodeBase64WithString:(NSString *)strBase64; + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey context:(CCOperation)encryptOrDecrypt; @end @implementation JoDes + (NSString *) encode:(NSString *)str key:(NSString *)key { // doCipher 不能编汉字,所以要进行 url encode NSMutableString* str1 = [JoDes urlEncode:str]; NSMutableString* encode = [NSMutableString stringWithString:[JoDes doCipher:str1 key:key context:kCCEncrypt]]; [JoDes formatSpecialCharacters:encode]; return encode; } + (NSString *) decode:(NSString *)str key:(NSString *)key { NSMutableString *str1 = [NSMutableString stringWithString:str]; [JoDes reformatSpecialCharacters:str1]; NSString *rt = [JoDes doCipher:str1 key:key context:kCCDecrypt]; return rt; } + (NSMutableString *)urlEncode:(NSString*)str { NSMutableString* encodeStr = [NSMutableString stringWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; [encodeStr replaceOccurrencesOfString:@"+" withString:@"%2B" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])]; [encodeStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])]; return encodeStr; } + (void)formatSpecialCharacters:(NSMutableString *)str { [str replaceOccurrencesOfString:@"+" withString:@"$$" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])]; [str replaceOccurrencesOfString:@"/" withString:@"@@" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])]; } + (void)reformatSpecialCharacters:(NSMutableString *)str { [str replaceOccurrencesOfString:@"$$" withString:@"+" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])]; [str replaceOccurrencesOfString:@"@@" withString:@"/" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [str length])]; } + (NSString *)encodeBase64WithString:(NSString *)strData { return [JoDes encodeBase64WithData:[strData dataUsingEncoding:NSUTF8StringEncoding]]; } + (NSString *)encodeBase64WithData:(NSData *)objData { NSString *encoding = nil; unsigned char *encodingBytes = NULL; @try { static char encodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static NSUInteger paddingTable[] = {0,2,1}; NSUInteger dataLength = [objData length]; NSUInteger encodedBlocks = (dataLength * 8) / 24; NSUInteger padding = paddingTable[dataLength % 3]; if( padding > 0 ) encodedBlocks++; NSUInteger encodedLength = encodedBlocks * 4; encodingBytes = malloc(encodedLength); if( encodingBytes != NULL ) { NSUInteger rawBytesToProcess = dataLength; NSUInteger rawBaseIndex = 0; NSUInteger encodingBaseIndex = 0; unsigned char *rawBytes = (unsigned char *)[objData bytes]; unsigned char rawByte1, rawByte2, rawByte3; while( rawBytesToProcess >= 3 ) { rawByte1 = rawBytes[rawBaseIndex]; rawByte2 = rawBytes[rawBaseIndex+1]; rawByte3 = rawBytes[rawBaseIndex+2]; encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)]; encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ]; encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) | ((rawByte3 >> 6) & 0x03) ]; encodingBytes[encodingBaseIndex+3] = encodingTable[(rawByte3 & 0x3F)]; rawBaseIndex += 3; encodingBaseIndex += 4; rawBytesToProcess -= 3; } rawByte2 = 0; switch (dataLength-rawBaseIndex) { case 2: rawByte2 = rawBytes[rawBaseIndex+1]; case 1: rawByte1 = rawBytes[rawBaseIndex]; encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)]; encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ]; encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) ]; // we can skip rawByte3 since we have a partial block it would always be 0 break; } // compute location from where to begin inserting padding, it may overwrite some bytes from the partial block encoding // if their value was 0 (cases 1-2). encodingBaseIndex = encodedLength - padding; while( padding-- > 0 ) { encodingBytes[encodingBaseIndex++] = '='; } encoding = [[NSString alloc] initWithBytes:encodingBytes length:encodedLength encoding:NSASCIIStringEncoding]; } } @catch (NSException *exception) { encoding = nil; NSLog(@"WARNING: error occured while tring to encode base 32 data: %@", exception); } @finally { if( encodingBytes != NULL ) { free( encodingBytes ); } } return encoding; } + (NSData *)decodeBase64WithString:(NSString *)strBase64 { NSData *data = nil; unsigned char *decodedBytes = NULL; @try { #define __ 255 static char decodingTable[256] = { __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F __,__,__,__, __,__,__,__, __,__,__,62, __,__,__,63, // 0x20 - 0x2F 52,53,54,55, 56,57,58,59, 60,61,__,__, __, 0,__,__, // 0x30 - 0x3F __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F __,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, // 0x60 - 0x6F 41,42,43,44, 45,46,47,48, 49,50,51,__, __,__,__,__, // 0x70 - 0x7F __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF }; strBase64 = [strBase64 stringByReplacingOccurrencesOfString:@"=" withString:@""]; NSData *encodedData = [strBase64 dataUsingEncoding:NSASCIIStringEncoding]; unsigned char *encodedBytes = (unsigned char *)[encodedData bytes]; NSUInteger encodedLength = [encodedData length]; NSUInteger encodedBlocks = (encodedLength+3) >> 2; NSUInteger expectedDataLength = encodedBlocks * 3; unsigned char decodingBlock[4]; decodedBytes = malloc(expectedDataLength); if( decodedBytes != NULL ) { NSUInteger i = 0; NSUInteger j = 0; NSUInteger k = 0; unsigned char c; while( i < encodedLength ) { c = decodingTable[encodedBytes[i]]; i++; if( c != __ ) { decodingBlock[j] = c; j++; if( j == 4 ) { decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4); decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2); decodedBytes[k+2] = (decodingBlock[2] << 6) | (decodingBlock[3]); j = 0; k += 3; } } } // Process left over bytes, if any if( j == 3 ) { decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4); decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2); k += 2; } else if( j == 2 ) { decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4); k += 1; } data = [[NSData alloc] initWithBytes:decodedBytes length:k]; } } @catch (NSException *exception) { data = nil; NSLog(@"WARNING: error occured while decoding base 32 string: %@", exception); } @finally { if( decodedBytes != NULL ) { free( decodedBytes ); } } return data; } + (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey context:(CCOperation)encryptOrDecrypt { NSStringEncoding EnC = NSUTF8StringEncoding; NSMutableData *dTextIn; if (encryptOrDecrypt == kCCDecrypt) { dTextIn = [[JoDes decodeBase64WithString:sTextIn] mutableCopy]; } else{ dTextIn = [[sTextIn dataUsingEncoding: EnC] mutableCopy]; } NSMutableData * dKey = [[sKey dataUsingEncoding:EnC] mutableCopy]; [dKey setLength:kCCBlockSizeDES]; uint8_t *bufferPtr1 = NULL; size_t bufferPtrSize1 = 0; size_t movedBytes1 = 0; //uint8_t iv[kCCBlockSizeDES]; //memset((void *) iv, 0x0, (size_t) sizeof(iv)); // Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF}; bufferPtrSize1 = ([sTextIn length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1); bufferPtr1 = malloc(bufferPtrSize1 * sizeof(uint8_t)); memset((void *)bufferPtr1, 0x00, bufferPtrSize1); CCCrypt(encryptOrDecrypt, // CCOperation op kCCAlgorithmDES, // CCAlgorithm alg kCCOptionPKCS7Padding, // CCOptions options [dKey bytes], // const void *key [dKey length], // size_t keyLength // [dKey bytes], // const void *iv [dTextIn bytes], // const void *dataIn [dTextIn length], // size_t dataInLength (void *)bufferPtr1, // void *dataOut bufferPtrSize1, // size_t dataOutAvailable &movedBytes1); //[dTextIn release]; //[dKey release]; NSString * sResult; if (encryptOrDecrypt == kCCDecrypt){ sResult = [[NSString alloc] initWithData:[NSData dataWithBytes:bufferPtr1 length:movedBytes1] encoding:EnC]; free(bufferPtr1); } else { NSData *dResult = [NSData dataWithBytes:bufferPtr1 length:movedBytes1]; free(bufferPtr1); sResult = [JoDes encodeBase64WithData:dResult]; } return sResult; } @end
相关推荐
在这个主题中,我们将探讨PHP、JAVA、C#、Object-C和Android这五种编程语言中如何实现DES加密解密。 1. PHP DES加密解密: 在PHP中,可以使用mcrypt扩展来实现DES加密解密。首先,你需要创建一个密钥和初始化向量...
本篇将深入探讨"C# winform DES加密解密"这一主题,帮助你理解如何在Windows Forms应用程序中实现数据的加密和解密。 DES(Data Encryption Standard)是一种经典的对称加密算法,它使用56位的密钥对数据进行加密和...
在C#中,我们可以使用`System.Security.Cryptography`命名空间下的`DESCryptoServiceProvider`类来实现DES加密和解密。需要注意的是,由于DES的弱点,现在更推荐使用更安全的AES(Advanced Encryption Standard)...
网上的类,很感兴趣,写了这个DES文件加密程序,已测试通过。 补充 button3_Click改为下述代码: private void button3_Click(object sender, EventArgs e) { sFileIn = this.textBox1.Text; sFileOut = this....
自己写的简单DES加密加密 public partial class _Default : System.Web.UI.Page { private static byte[] Key64 = { 42, 16, 93, 156, 78, 4, 218, 32 }; private static byte[] IV64 = { 55, 103, 246, 79, 36, ...
图19.3 使用ROT13算法加密解密数据 关 键技术 本实例实现时,主要是用Convert 类的ToChar 方法来获取单个字符的Unicode 编码,然后将字母的前13 个和后13 个对调,从而实现加密的功能。下面对Convert类的ToChar 方法...
Delphi是一种流行的Object Pascal编程环境,它提供了丰富的库和工具来支持开发工作,包括加解密功能。在这个特定的场景中,我们关注的是一个名为"Cryptography"的封装单元,它专门为Delphi开发者提供了对AES、DES和...
### c#使用DES解密提示:指定键的大小对于此算法无效 ...通过以上讨论和示例代码,我们可以看到在C#中处理DES加密解密时需要注意的细节。遵循这些指南可以帮助避免出现“指定键的大小对于此算法无效”的错误。
在IT行业中,字串加密解密是信息安全领域的重要部分,特别是在网络通信和服务中,如WebService。WebService是一种基于标准的、平台无关的通信机制,用于不同系统间的交互。在这个"字串加密解密WebService服务的源码...
DES加密解密 DES(Data Encryption Standard)是一种广泛使用的对称加密算法。下面的方法展示了如何使用C#实现基于DES的加密和解密操作。 ##### 加密方法定义: ```csharp public static String Encrypt(String ...
接着创建一个实现类`encryption`,它实现了`IEncryption`接口,并提供了具体的加密逻辑,如3DES加密。 在PowerBuilder中,调用C# DLL需要通过COM接口。首先,PB需要引用C# DLL,这可以通过在PB的“工具箱”中添加新...
- Blowfish算法是一种对称加密算法,C#中可以使用`System.Security.Cryptography`命名空间下的类来实现加密解密。Blowfish的实现涉及密钥扩展和Feistel网络。 - n-tier架构是一种分布式系统架构,通常包括表示层、...
5. **加密解密**:`EncryptionDES.cs`和`EncryptionHelper.cs`可能提供了数据加密和解密的功能,用于保护存储在数据库中的敏感信息。DES(Data Encryption Standard)是一种常用的对称加密算法,适用于小规模数据的...
1. **加密解密**: C#提供了System.Security.Cryptography命名空间,包含了多种加密算法,如AES(高级加密标准)、DES(数据加密标准)、RSA(公钥加密技术)等。通过这些类,你可以实现数据的安全存储和传输。 2....
在VB或C#中实现Blowfish涉及密钥生成、字节拆分、加密和解密过程,由于篇幅限制,这里不提供具体代码。 - n-tier架构是一种分布式应用设计模式,通常包括表现层、业务逻辑层、数据访问层等。例如,对于一个包含...
这里我们关注的"C#常用类库"主要涉及到缓存管理、加密解密、JSON序列化与反序列化、图像处理、MD5哈希、验证机制、Windows Communication Foundation (WCF)服务、XML操作等多个方面。以下将详细解析这些关键知识点:...
例3 - 例2的加密版 项目:就是讲例2通过DES 加密进行通讯的例子 连接测试工具 项目:很多朋友问我要连接数量测试工具。我一起的真的丢了。找不到了。所以重新写了一个 例4 项目:好多人让我写一个发送文件的例子,...
利用该方法加密,然后再结合其他加密方式,比如AES,DES等,可以有效的保证你的数据安全! C#源代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using ...
///StringEncrypt() DES字符串加密中文不可以加密 ///StringDecrypt()DES解密字符串 ///StringMD5Encrypt()MD5加密 ///StringPYChar()单个汉字返回该汉字首字母 ///StringRandom()生成指定位数的随机数 //...