- 慧慧
-
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 java.io.IOException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DES {
private byte[] desKey;
public DES(String desKey) {
this.desKey = desKey.getBytes();
}
public byte[] desEncrypt(byte[] plainText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
byte data[] = plainText;
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
}
public byte[] desDecrypt(byte[] encryptText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
byte encryptedData[] = encryptText;
byte decryptedData[] = cipher.doFinal(encryptedData);
return decryptedData;
}
public String encrypt(String input) throws Exception {
return base64Encode(desEncrypt(input.getBytes()));
}
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 sun.misc.BASE64Encoder();
return b.encode(s);
}
public static byte[] base64Decode(String s) throws IOException {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
return b;
}
public static void main(String[] args) throws Exception {
String key = "abcdefgh";
String input = "a";
DES crypt = new DES(key);
System.out.println("Encode:" + crypt.encrypt(input));
System.out.println("Decode:" + crypt.decrypt(crypt.encrypt(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