PHP实现和c#一致的DES加密解密,可以从网上搜到一大堆,但是测试后发现都没法用。以下正确代码是我经过苦苦才找到的。希望大家在系统整合时能用的上。
注意:key的长度为8位以内。
[csharp] view plain copy print//C# 版DES 加解密算法
using System;
using SystemData;
using SystemConfiguration;
using SystemWeb;
using SystemWebSecurity;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIWebControlsWebParts;
using SystemWebUIHtmlControls;
using SystemDataSqlClient;
using SystemSecurityCryptography;
using SystemIO;
using SystemText;
public class Des{
//加解密密钥
private static string skey = "12345678";
//初始化向量
private static byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
#region DESEnCode DES加密
public static string DESEnCode(string pToEncrypt, string sKey)
{
pToEncrypt = >}[php] view plain copy print
<php
class DES
{
var $key;
var $iv; //偏移量
function DES( $key, $iv=0 ) {
//key长度8例如:1234abcd
$this->key = $key;
if( $iv == 0 ) {
$this->iv = $key; //默认以$key 作为 iv
} else {
$this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM );
}
}
function encrypt($str) {
//加密,返回大写十六进制字符串
$size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );
$str = $this->pkcs5Pad ( $str, $size );
return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) );
}
function decrypt($str) {
//解密
$strBin = $this->hex2bin( strtolower( $str ) );
$str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv );
$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 );
}
}
>
IOS:引入ios自带库 #include
先以DES加密算法为例讲解,DES的加密和解密都同用一个Key,下面两个加解密函数如下:
//加密
-(NSString ) encryptUseDES:(NSString )clearText key:(NSString )key
{
//一般对加密的字符串采用UTF-8编码 NSData存储的就是二进制数据
NSData data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block
//确定加密过后的字符串在内存中存放的大小,根据文档,对于块密码方式(这个库还包括流密码方式)
//加密过后的字符串大小总是小于或等于加密之前数据的大小加上对应加密算法的块大小
//但看到一些大牛还这样一下 & ~(kCCBlockSizeDES - 1) 目前不知道为嘛
size_t bufferSize = ([data length] + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
//void buffer = malloc(bufferSize);//可以手动创建buffer,但之后要记得free掉
unsigned char buffer[bufferSize]; //定义输出加密串所占内存空间
memset(buffer, 0, sizeof(char)); //采用ios中宏定义好的方法分配空间,可免去手动free
size_t numBytesEncrypted = 0; //输出加密串的字节数
//加密数据,采用库中的CCCrypt方法,这个方法会按次序执行CCCrytorCreate(),
// CCCryptorUpdate(), CCCryptorFinal(), and CCCryptorRelease() 如果开发者自己create这个对象,
//那么后面就必须执行final、release之类的函数,CCCrypt方法一次性解决
// Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
//Byte iv[] = {1,2,3,4,5,6,7,8}; 加密所需的随机字符
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, //加密方式,kCCEncrypt加密 kCCDecrypt解密
kCCAlgorithmDES, //采用的加密算法,内置包含AES、DES、
//3DES、其他还有四个,不知道是什么
//后续讨论
//加密额外参数,注意此处各个平台之间指定的时候要记得一样
kCCOptionPKCS7Padding | kCCOptionECBMode,
[key UTF8String], //加密密匙 UTF8的字符串
kCCKeySizeDES, //密匙长度字节 各算法有对应的长度宏
nil, //随机字符,可指定也可不指定,各平台之间不绝对
[data bytes], //待加密串的字节长度
[data length], //待加密串的长度
buffer, //输出已加密串的内存地址
bufferSize, //已加密串的大小
&numBytesEncrypted);
NSString plainText = nil;
if (cryptStatus == kCCSuccess) {
NSData dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
plainText = [GTMBase64 stringByEncodingData:dataTemp];
}else{
NSLog(@"DES加密失败");
}
return plainText;
}
//解密
-(NSString) decryptUseDES:(NSString)cipherText key:(NSString)key {
// 利用 GTMBase64 解码 Base64 字串
NSData cipherData = [GTMBase64 decodeString:cipherText];
size_t bufferSize = ([cipherData length] + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
//unsigned char buffer[1024];
unsigned char buffer[bufferSize];
memset(buffer, 0, sizeof(char));
size_t numBytesDecrypted = 0;
// IV 偏移量不需使用
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding | kCCOptionECBMode,
[key UTF8String],
kCCKeySizeDES,
nil,
[cipherData bytes],
[cipherData length],
buffer,
bufferSize,//1024,
&numBytesDecrypted);
NSString plainText = nil;
if (cryptStatus == kCCSuccess) {
NSData data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
plainText = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
return plainText;
}
java和php平台的代码实现:
Java代码 收藏代码
import javaioIOException;
import javasecuritySecureRandom;
import javaxcryptoCipher;
import javaxcryptoSecretKey;
import javaxcryptoSecretKeyFactory;
import javaxcryptospecDESKeySpec;
import sunmiscBASE64Decoder;
import sunmiscBASE64Encoder;
public class DES {
private byte[] desKey;
public DES(String desKey) {
thisdesKey = desKeygetBytes();
}
public byte[] desEncrypt(byte[] plainText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactorygetInstance("DES");
SecretKey key = keyFactorygenerateSecret(dks);
Cipher cipher = CiphergetInstance("DES");
cipherinit(CipherENCRYPT_MODE, key, sr);
byte data[] = plainText;
byte encryptedData[] = cipherdoFinal(data);
return encryptedData;
}
public byte[] desDecrypt(byte[] encryptText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactorygetInstance("DES");
SecretKey key = keyFactorygenerateSecret(dks);
Cipher cipher = CiphergetInstance("DES");
cipherinit(CipherDECRYPT_MODE, key, sr);
byte encryptedData[] = encryptText;
byte decryptedData[] = cipherdoFinal(encryptedData);
return decryptedData;
}
public String encrypt(String input) throws Exception {
return base64Encode(desEncrypt(inputgetBytes()));
}
public String decrypt(String input) throws Exception {
byte[] result = base64Decode(input);
return new String(desDecrypt(result));
}
public static String base64Encode(byte[] s) {
if (s == null)
return null;
BASE64Encoder b = new sunmiscBASE64Encoder();
return bencode(s);
}
public static byte[] base64Decode(String s) throws IOException {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoderdecodeBuffer(s);
return b;
}
public static void main(String[] args) throws Exception {
String key = "abcdefgh";
String input = "a";
DES crypt = new DES(key);
Systemoutprintln("Encode:" + cryptencrypt(input));
Systemoutprintln("Decode:" + cryptdecrypt(cryptencrypt(input)));
}
}
php 方法一
Php代码 收藏代码
<php
class DES1 {
var $key;
function DES1($key) {
$this->key = $key;
}
function encrypt($input) {
$size = mcrypt_get_block_size('des', 'ecb');
$input = $this->pkcs5_pad($input, $size);
$key = $this->key;
$td = mcrypt_module_open('des', '', 'ecb', '');
$iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
@mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = base64_encode($data);
return $data;
}
function decrypt($encrypted) {
$encrypted = base64_decode($encrypted);
$key =$this->key;
$td = mcrypt_module_open('des','','ecb','');
//使用MCRYPT_DES算法,cbc模式
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
@mcrypt_generic_init($td, $key, $iv);
//初始处理
$decrypted = mdecrypt_generic($td, $encrypted);
//解密
mcrypt_generic_deinit($td);
//结束
mcrypt_module_close($td);
$y=$this->pkcs5_unpad($decrypted);
return $y;
}
function pkcs5_pad ($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text str_repeat(chr($pad), $pad);
}
function pkcs5_unpad($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);
}
}
$key = "abcdefgh";
$input = "a";
$crypt = new DES1($key);
echo "Encode:"$crypt->encrypt($input)"<br/>";
echo "Decode:"$crypt->decrypt($crypt->encr
$key = "This is supposed to be a secret key !!!";
function keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++) {
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function encrypt($txt,$key)
{
srand((double)microtime()1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++) {
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp= substr($encrypt_key,$ctr,1)
(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
$ctr++;
}
return keyED($tmp,$key);
}
function decrypt($txt,$key)
{
$txt = keyED($txt,$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++) {
$md5 = substr($txt,$i,1);
$i++;
$tmp= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
$string = "Hello World !!!";
// encrypt $string, and store it in $enc_text
$enc_text = encrypt($string,$key);
// decrypt the encrypted text $enc_text, and store it in $dec_text
$dec_text = decrypt($enc_text,$key);
//加密
function str2hex($s)
{
$r = "";
$hexes = array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
for ($i=0; $i<strlen($s); $i++) ="" $r = ($hexes [(ord($s{$i}) >> 4)] $hexes [(ord($s{$i}) & 0xf)]);
return $r;
}
//解密
function hex2str($s)
{
$r = "";
for ( $i = 0; $i<strlen($s); $i="" +="2) " {
$x1 = ord($s{$i});
$x1 = ($x1>=48 && $x1<58) $x1-48 : $x1-97+10;
$x2 = ord($s{$i+1});
$x2 = ($x2>=48 && $x2<58) $x2-48 : $x2-97+10;
$r = chr((($x1 << 4) & 0xf0) | ($x2 & 0x0f));
}
return $r;
}
echo str2hex("山东");
echo "
";
echo hex2str("c9bdb6ab");
>
用Zend的加密吧,但是还是可以解密的,这也没办法,凡是对称加密或非不可逆的加密算法,均可以解密,这只是时间问题。特别是没有密码的加密(不可逆除外)。可以这样,使用AES加密,再用GZIP压缩,然后运行时解密,在eval那些代码。前提是每个加密的文件的密码都不同,要购买才可以解密运行。
这个应该是gzip压缩。
用个解压缩的就行。
function gzip_decode ($data) {
$flags = ord(substr($data, 3, 1));
$headerlen = 10;
$extralen = 0;
$filenamelen = 0;
if ($flags & 4) {
$extralen = unpack('v' ,substr($data, 10, 2));
$extralen = $extralen[1];
$headerlen += 2 + $extralen;
}
if ($flags & 8) // Filename
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 16) // Comment
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 2) // CRC at end of file
$headerlen += 2;
$unpacked = @gzinflate(substr($data, $headerlen));
if ($unpacked === FALSE)
$unpacked = $data;
return $unpacked;
}
虽然md5是不可逆的加密方式,但是网上还是可以解密的,在线解密md5运用的是一次md5加密方式去解析的,解析的方式也是运用强大的数据内容一
一去对比的,找到匹配的就可以了。在程序中你可以多次用md5加密和字符串截取,或者追加字符串,比如密码,传来的值用同样的方式加密和数据库保存的密码做对比就可以了,这样安全性会很高,再强大的md5数据库内容也找不到你设置的密码
以上就是关于如何用php实现和c#一致的DES加密解密全部的内容,包括:如何用php实现和c#一致的DES加密解密、php加密文件 解密data 转nsstring 为nil. rc4 ios、php代码加密怎么解密等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)