iosjavaaes加密解密
Ⅰ php加密文件 解密data 轉nsstring 為nil. rc4 ios
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_mole_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_mole_close($td);
$data = base64_encode($data);
return $data;
}
function decrypt($encrypted) {
$encrypted = base64_decode($encrypted);
$key =$this->key;
$td = mcrypt_mole_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_mole_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