I'm looking for a way to decrypt a file since a few weeks. But it's impossible to recover the file intact in PHP, only with node. But I would like to do it without node.
If someone can tell me where I could be wrong... ?
I tried with openssl_encrypt/decrypt then with OPENSSL_NO_PADDING & ZERO_PADDING options. Transform the result in base64 but impossible to have the good result...
I thank you in advance I do not know what to do...
Here is my NodeJs crypto code :
decrypt(encryptedBuffer) {
const PASSPHRASE = "";
let decryptedBuffer = Buffer.alloc(encryptedBuffer.length);
let chunkSize = 2048;
let progress = 0;
while (progress < encryptedBuffer.length) {
if ((encryptedBuffer.length - progress) < 2048) {
chunkSize = encryptedBuffer.length - progress;
}
let encryptedChunk = encryptedBuffer.slice(progress, progress + chunkSize);
// Only decrypt every third chunk and only if not at the end
if (progress % (chunkSize * 3) === 0 && chunkSize === 2048) {
let cipher = crypto.createDecipheriv('bf-cbc', PASSPHRASE, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7]));
cipher.setAutoPadding(false);
encryptedChunk = Buffer.concat([cipher.update(encryptedChunk), cipher.final()]);
}
decryptedBuffer.write(encryptedChunk.toString('binary'), progress, encryptedChunk.length, 'binary');
progress += chunkSize;
}
return decryptedBuffer;
}
Here in PHP
public function decrypt($encryptedBuffer)
{
ini_set('memory_limit', '1G');
$f = fopen('myfile', 'wb+');
$chunkSize = 2048;
$progress = 0;
$passphrase = "h5ihb>p9`'yjmkhf";
while ($progress > strlen($encryptedBuffer)) {
// If the buffer is if the end calculate the valid chunksize
if ((strlen($encryptedBuffer) - $progress) < 2048) {
$chunkSize = strlen($encryptedBuffer) - $progress;
}
/** Getting the encrypted chunk part */
$encryptedChunk = substr($encryptedBuffer, $progress, $progress + $chunkSize);
// Only decrypt every third chunk and only if not at the end
if ($progress % ($chunkSize * 3) === 0 && $chunkSize === 2048) {
$encryptedChunk = openssl_decrypt($encryptedChunk, 'bf-cbc', $passphrase, OPENSSL_ZERO_PADDING, '01234567');
}
fwrite($f, $encryptedChunk);
$progress += $chunkSize;
}
}
There are several flaws in the PHP code:
The condition in the while loop is wrong and should be:
$progress < strlen($encryptedBuffer).
$encryptedChunk is determined incorrectly because substr() expects the length in the third parameter. The correct way is:
$encryptedChunk = substr($encryptedBuffer, $progress, $chunkSize);
In the openssl_decrypt() call, too few flags are set in the fourth parameter:
Apart from disabling the padding, the default Base64 decoding has to be disabled with OPENSSL_RAW_DATA.
For key sizes smaller than 16 bytes, the padding of the key with 0x00 values to a length of 16 bytes has to be disabled with OPENSSL_DONT_ZERO_PAD_KEY. This is a PHP bug (s. here). The fix, i.e. the flag is available as of version 7.1.8.
Overall: OPENSSL_DONT_ZERO_PAD_KEY | OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING.
The wrong IV is used, correct would be: hex2bin('0001020304050607').
With these changes, decryption with the PHP code works.
Regarding security: The short block size makes Blowfish vulnerable to birthday attacks, see here. Using a static IV is generally insecure. Rather, a random IV should be generated for each encryption.
Related
I'm trying to generate an access token in php for user authorization
I used the following:
base64_encode(com_create_guid());
is this correct use in this context? and what is meant by "cryptographically secure"?
EDIT:
First, I was going to generate a random string using a function like this,
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
but then I read about the token has to be cryptographically secure, and I can't really get what is this exactly or precisely.
then I went to com_create_guid() , but I noticed that com_create_guid() generates UUID, which does not include all characters (just numbers + a-f of hex). So I thought that base64 encoding may be suitable to convert this into a full character token (not for security).
here I'm asking about this being suitable for generating an access token, and if not is there a better way for generating it?
Returns a random string with crypto-strength given in $len. The string is always longer than $len by 3-4 expansion (that is, it takes 4 characters to encode 3 length). Pass a $len of at least 16 for good strength.
Stolen from https://stackoverflow.com/a/8429944/14768 and edited to use /dev/random instead of /dev/urandom
function generateRandomString($len)
{
$fp = #fopen('/dev/random','rb');
$result = '';
if ($fp !== FALSE) {
$result .= #fread($fp, $len);
#fclose($fp);
}
else
{
trigger_error('Can not open /dev/urandom.');
}
// convert from binary to string
$result = base64_encode($result);
// remove none url chars
$result = strtr($result, '+/', '-_');
// Remove = from the end
$result = str_replace('=', ' ', $result);
return $result;
}
When wanting crypt-strength stuff use crypt-strength stuff. guidv4 is not guaranteed to be crypt-strength.
You might want to use this:
function guidv4()
{
if (function_exists('com_create_guid') === true)
return trim(com_create_guid(), '{}');
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
source: http://php.net/manual/en/function.com-create-guid.php#117893
This code is more cryptographically secure, however, for what you are doing you should be fine.
Cryptographically secure in layman's terms is something that is random, and is hard to recreate or predict.
Please do not mark it as duplicate. I have already gone through almost all the previous post for same issue, but was not able to tackle my error.
I am trying to upgrade the Sagepay Protocol from v2.23 to v3.00
I have also deployed PHP kit provided by Sagepay and getting the same error.
Below is the AES encryption I am using to make it compatible for v3.00 in my includes.php
Any guidance would be much appreciated.
<?
/* Base 64 Encoding function **
** PHP does it natively but just for consistency and ease of maintenance, let's declare our own function **/
function base64Encode($plain) {
// Initialise output variable
$output = "";
// Do encoding
$output = base64_encode($plain);
// Return the result
return $output;
}
/* Base 64 decoding function **
** PHP does it natively but just for consistency and ease of maintenance, let's declare our own function **/
function base64Decode($scrambled) {
// Initialise output variable
$output = "";
// Fix plus to space conversion issue
$scrambled = str_replace(" ","+",$scrambled);
// Do encoding
$output = base64_decode($scrambled);
// Return the result
return $output;
}
/* The SimpleXor encryption algorithm **
** NOTE: This is a placeholder really. Future releases of Form will use AES or TwoFish. Proper encryption **
** This simple function and the Base64 will deter script kiddies and prevent the "View Source" type tampering **
** It won't stop a half decent hacker though, but the most they could do is change the amount field to something **
** else, so provided the vendor checks the reports and compares amounts, there is no harm done. It's still **
** more secure than the other PSPs who don't both encrypting their forms at all */
function simpleXor($InString, $Key) {
// Initialise key array
$KeyList = array();
// Initialise out variable
$output = "";
// Convert $Key into array of ASCII values
for($i = 0; $i < strlen($Key); $i++){
$KeyList[$i] = ord(substr($Key, $i, 1));
}
// Step through string a character at a time
for($i = 0; $i < strlen($InString); $i++) {
// Get ASCII code from string, get ASCII code from key (loop through with MOD), XOR the two, get the character from the result
// % is MOD (modulus), ^ is XOR
$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
}
// Return the result
return $output;
}
//** Wrapper function do encrypt an encode based on strEncryptionType setting **
function encryptAndEncode($strPost) {
global $strEncryptionType
,$strEncryptionPassword;
if ($strEncryptionType=="XOR")
{
//** XOR encryption with Base64 encoding **
return base64Encode(simpleXor($strPost,$strEncryptionPassword));
}
else
{
//** AES encryption, CBC blocking with PKCS5 padding then HEX encoding - DEFAULT **
//** use initialization vector (IV) set from $strEncryptionPassword
$strIV = $strEncryptionPassword;
//** add PKCS5 padding to the text to be encypted
$strPost = addPKCS5Padding($strPost);
//** perform encryption with PHP's MCRYPT module
$strCrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $strEncryptionPassword, $strPost, MCRYPT_MODE_CBC, $strIV);
//** perform hex encoding and return
return "#" . bin2hex($strCrypt);
}
}
//** Wrapper function do decode then decrypt based on header of the encrypted field **
function decodeAndDecrypt($strPost) {
global $strEncryptionPassword;
if (substr($strPost,0,1)=="#")
{
//** HEX decoding then AES decryption, CBC blocking with PKCS5 padding - DEFAULT **
//** use initialization vector (IV) set from $strEncryptionPassword
$strIV = $strEncryptionPassword;
//** remove the first char which is # to flag this is AES encrypted
$strPost = substr($strPost,1);
//** HEX decoding
$strPost = pack('H*', $strPost);
//** perform decryption with PHP's MCRYPT module
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $strEncryptionPassword, $strPost, MCRYPT_MODE_CBC, $strIV);
}
else
{
//** Base 64 decoding plus XOR decryption **
return simpleXor(base64Decode($strPost),$strEncryptionPassword);
}
}
//** PHP's mcrypt does not have built in PKCS5 Padding, so we use this
function addPKCS5Padding($input)
{
$blocksize = 16;
$padding = "";
// Pad input to an even block size boundary
$padlength = $blocksize - (strlen($input) % $blocksize);
for($i = 1; $i <= $padlength; $i++) {
$padding .= chr($padlength);
}
return $input . $padding;
}
/*************
function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
//echo "<br/>Padding:".str_repeat(chr($pad), $pad)."<";
return $text . str_repeat(chr($pad), $pad);
}
function encryptFieldData($input)
{
$key = "[mykey]";
$iv = $key;
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
if (mcrypt_generic_init($cipher, $key, $iv) != -1)
{
$cipherText = mcrypt_generic($cipher,$input );
mcrypt_generic_deinit($cipher);
$enc = bin2hex($cipherText);
}
return $enc;
}
$str = "Currency=GBP";
$datapadded = pkcs5_pad($str,16);
$cryptpadded = "#" . encryptFieldData($datapadded);
*************************/
?>
The problem was with my server mcrypt PHP extension. It wasn't install/enable on the server. I must have consider this before making all test attempts.
Thank you all for the efforts towards my issue.
Have you checked your encryption password is correct? 3045 is the first error to be thrown if the password is wrong. This is not so nuts as it sounds - encryption passwords are different between test and live.....
I have a PHP application that needs to encrypt a challenge string that is consumed by an ASP.net web service however the output of my PHP implementation is not properly decrypted by .net. Exactly as in this question relating to iOS and .net: AES128 bit encryption string is not similar as on .net
Why are the outputs different and what can I do to my PHP to output the same as .net?
My PHP code looks like this:
$key = '128bit-16bytekey';
$value = '128bit-16byteval';
function fnEncrypt($value, $key)
{
$ivsize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($ivsize);
return base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$key, $value,
MCRYPT_MODE_ECB,$iv
));
}
.net like this
public static string EncryptData(string plainText)
{
string encryptionKey = AppConstants.AES_ENCRYPTDECRYPT_KEY;
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] keyBytes = new byte[16];
byte[] tempKey = encoding.GetBytes(encryptionKey);
for (int i = 0; i < keyBytes.Length; i++)
{
if (i < tempKey.Length)
{
keyBytes[i] = tempKey[i];
}
else
{
keyBytes[i] = 0;
}
}
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
//AesManaged symmetricKey = new AesManaged();
//symmetricKey.Padding = PaddingMode.PKCS7;
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.ECB;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
//ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, null);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = Convert.ToBase64String(cipherTextBytes);
// Return encrypted string.
return cipherText;
}
Sample outputs
PHP : Q54nP/tXq2rDTUwWw4ckkg==
.net : Q54nP/tXq2rDTUwWw4ckkpSt9CQiIzsg2xsQEndcqc8=
PHP : DQZdAB/lABXVOOoCdNM6HQ==
.net : DQZdAB/lABXVOOoCdNM6HZSt9CQiIzsg2xsQEndcqc8=
As in the question ref'd above the right hand side of the .net output are always the same and left side are consistent between the two implementations. I am pretty sure the IV is irrelevant and that it is something to do with how padding is handled in mcrypt.
If I decrypt either of the outputs in PHP it returns the same correct result.
Can anyone shed any light? I am unable to change the .net app. Thanks!
This happens due to the padding that is applied in .net. You can overcome this by adding the following line to your .net code:
symmetricKey.Padding = PaddingMode.None;
Or you can change the PHP code to get the same encrypted string:
// Add the lines below to your fnEncrypt function
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$len = strlen($value);
$padding = $block - ($len % $block);
$value .= str_repeat(chr($padding),$padding);
A similar issue is described in one of the comments from PHP manual pages: http://www.php.net//manual/en/function.mcrypt-encrypt.php#47973
I 'm stuck. It seems that AES encryption done by PHP cannot be decrypted in windows.
PHP code:
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,"12345678", "test", MCRYPT_MODE_CBC));
Windows Code:
"s" has the string which is created by the above response after converting back from base64.
bool Decrypt(char* s,char* key,char* dest)
{
// Create the crypto provider context.
HCRYPTPROV hProvider = NULL;
if (!CryptAcquireContext(&hProvider,
NULL, // pszContainer = no named container
MS_ENH_RSA_AES_PROV, // pszProvider = default provider
PROV_RSA_AES,
0))
return false;
// Construct the blob necessary for the key generation.
aes128keyBlob aes_blob128;
aes_blob128.header.bType = PLAINTEXTKEYBLOB;
aes_blob128.header.bVersion = CUR_BLOB_VERSION;
aes_blob128.header.reserved = 0;
aes_blob128.header.aiKeyAlg = CALG_AES_128;
aes_blob128.keySize = 16;
memcpy(aes_blob128.bytes, key, 16);
HCRYPTKEY hKey = NULL;
if (!CryptImportKey(hProvider,
(BYTE*)(&aes_blob128),
sizeof(aes_blob128),
NULL, //
0, //
&hKey)) {
...
}
// Set Mode
DWORD dwMode = CRYPT_MODE_CBC;
CryptSetKeyParam( hKey, KP_MODE, (BYTE*)&dwMode, 0 );
DWORD length = 16;
BOOL X = CryptDecrypt(hKey,
NULL, // hHash = no hash
TRUE, // Final
0,
(BYTE*)s,
&length);
//int le = GetLastError();
memcpy(dest,s,16);
CryptDestroyKey(hKey);
CryptReleaseContext(hProvider, 0);
}
What could be wrong?
The information you provided is not enough to say for certain but I think that your problem is the key length.
In PHP code you pass "12345678" as a key. And AES128 has a key length of 128bit or 16 bytes.
PHP pads the remaining with zero bytes, as stated in the documentation on mcrypt_encrypt.
In the C++ code you pass only the pointer to your key buffer to Decrypt function. But then you copy 16 bytes from it to the key BLOB:
aes_blob128.keySize = 16;
memcpy(aes_blob128.bytes, key, 16);
Then if you call your function like:
char dest[16];
bool result = Decrypt(string_from_php,"12345678",dest);
than the 8 bytes that happen to reside in memory after the "12345678" constant will be copied to the key blob and passed to CryptImportKey as an actual key. Thus the key in C and in PHP code would be actually different and the decryption will fail due to padding error.
PHP MCRYPT functions are a bit different than the windows decryption functions.
Because the mcrypt function takes the key of any length and converts it to the length required by the algorithm by adding \0 at the end of key string.
Please note to create a key with the specified length required for the encryption by the algorithm on both sides.
use md5 on the key and then convert it to the length required for the algorithm.
See below URL
Encrypt in PHP, Decrypt in C# (WP7 / Silverlight) using AES / Rijndael
http://pumka.net/2009/12/16/rsa-encryption-cplusplus-delphi-cryptoapi-php-openssl-2/
http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B
Read it
I droped the MD5 crap out of PHP and C#, and they are now working properly.
Just in case you dropped here looking for the same answer, here is a sample code. Don't forget to make your own key and iv (although those bellow will work, is not recommended to use!)
PHP:
function encrypt128($message) {
$vector = "0000000000000000";
$key = "00000000000000000000000000000000";
$block = mcrypt_get_block_size('rijndael_128', 'cbc');
$pad = $block - (strlen($message) % $block);
$message .= str_repeat(chr($pad), $pad);
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $vector);
$result = mcrypt_generic($cipher, $message);
mcrypt_generic_deinit($cipher);
return base64_encode($result);
}
C++
Encrypt-Decrypt contacts database entries using Symbian C++
http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B
Headers Required:
#include <cntdb.h> // CContactDatabse,
#include <cntitem.h> //CContactItem,CContactItemFieldSet
http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B
Encrypt Contact Fields
void CEncryptContactContainer::EncryptAll()
{
CContactDatabase *contactDB = CContactDatabase::OpenL();
CleanupStack::PushL(contactDB);
TContactIter iter(*contactDB);
TContactItemId aContactId;
//Developer can take Heap based descriptor for large/unknown size of contact items.
TBuf16<70> aValue;
const CContactIdArray* contactArray = contactDB->SortedItemsL();
TInt cnt=contactArray->Count();
for(TInt i=0;i<cnt;i++)
{
CContactItem* contactItem=NULL;
contactItem= contactDB->OpenContactL((*contactArray)[i]);
CleanupStack::PushL(contactItem);
CContactItemFieldSet& fieldSet= contactItem->CardFields();
TInt fieldCount=fieldSet.Count(); // This will give number of contact fields.
for(TInt index=0; index < fieldCount; index++)
{
CContactItemField& field = fieldSet[index];
const CContentType& type = field.ContentType();
if(!(type.ContainsFieldType(KUidContactFieldBirthday)))
{
TPtrC name = contactItem->CardFields()[index].TextStorage()->Text();
aValue.Copy(name);
Encrypt(aValue); // Call real encyption here
contactItem->CardFields()[index].TextStorage()->SetTextL(aValue);
}
} //Inner for loop ends here
contactDB->CommitContactL(*contactItem);
CleanupStack::PopAndDestroy(contactItem);
} //Outer for loop ends here
CleanupStack::PopAndDestroy(contactDB);
}
void CEncryptContactContainer:: Encrypt (TDes& aValue)
{
for(TInt iCount=0; iCount< aValue.Length();iCount++)
{
aValue[iCount]+=3;
}
}
Decrypt Contact Fields
void CEncryptContactContainer::DecryptAll()
{
CContactDatabase *contactDB = CContactDatabase::OpenL();
CleanupStack::PushL(contactDB);
TContactIter iter(*contactDB);
TContactItemId aContactId;
TBuf16<70> aValue;
const CContactIdArray* contactArray = contactDB->SortedItemsL();
TInt cnt=contactArray->Count();
for(TInt i=0;i<cnt;i++)
{
CContactItem* contactItem=NULL;
contactItem= contactDB->OpenContactL((*contactArray)[i]);
CleanupStack::PushL(contactItem);
CContactItemFieldSet& fieldSet= contactItem->CardFields();
TInt fieldCount=fieldSet.Count(); // This will give number of contact fields.
for(TInt index=0; index < fieldCount; index++)
{
CContactItemField& field = fieldSet[index];
const CContentType& type = field.ContentType();
if(!(type.ContainsFieldType(KUidContactFieldBirthday)))
{
TPtrC name = contactItem->CardFields()[index].TextStorage()->Text();
aValue.Copy(name);
Decrypt(aValue);
contactItem->CardFields()[index].TextStorage()->SetTextL(aValue);
}
} //Inner for loop ends here
contactDB->CommitContactL(*contactItem);
CleanupStack::PopAndDestroy(contactItem);
} //Outer for loop ends here
CleanupStack::PopAndDestroy(contactDB);
}
void CEncryptContactContainer:: Decrypt (TDes& aValue)
{
for(TInt iCount=0; iCount< aValue.Length();iCount++)
{
aValue[iCount]-=3;
}
}
C#:
byte[] cripted = EncryptStringToBytes("Test", System.Text.Encoding.UTF8.GetBytes("00000000000000000000000000000000"), System.Text.Encoding.UTF8.GetBytes("0000000000000000"));
I have a XML file on a server encrypted with the RC4 algorithm (http://rc4crypt.devhome.org)
function encrypt ($pwd, $data, $ispwdHex = 0)
{
if ($ispwdHex)
$pwd = #pack('H*', $pwd); // valid input, please!
$key[] = '';
$box[] = '';
$cipher = '';
$pwd_length = strlen($pwd);
$data_length = strlen($data);
for ($i = 0; $i < 256; $i++)
{
$key[$i] = ord($pwd[$i % $pwd_length]);
$box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++)
{
$j = ($j + $box[$i] + $key[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $data_length; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$k = $box[(($box[$a] + $box[$j]) % 256)];
$cipher .= chr(ord($data[$i]) ^ $k);
}
return $cipher;
}
Here is the objective-C code I use to decrypt :
NSData *dataToDecrypt = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.url.com/fileCrypted.xml"]] returningResponse:nil error:nil];
const void *vplainText;
size_t plainTextBufferSize;
plainTextBufferSize = [dataToDecrypt length];
vplainText = [dataToDecrypt bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
NSString *key = #"mykey";
//NSString *initVec = #"init Vec";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];
size_t keyLength = [[key dataUsingEncoding:NSUTF8StringEncoding] length];
ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmRC4,
0,
vkey,
kCCKeySizeDES,
nil,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else*/ if (ccStatus == kCCParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED";
NSString *result = [[ NSString alloc ] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIEncoding];
Logs output : SUCCESS but my result is not good (I tested many encoding but ASCII seems to be the good, cf. PHP function ord ...)
Are my both RC4 implementation standard ?
Edit: removed IV in Objective-C code
Edit2: Objective-C KeyLength = password data length, removed option
If you don't know what you're doing in cryptography, then "rolling-your-own" is a sure fire receipe for disaster. You don't have to believe me, read John Viega on The Cult of Schneier about general programmers who try to "roll their own" cryptography. Paraphrased: Don't do it.
Since this is a file, and I'm guessing a reasonable small file, you can use more standard and higher level libraries using standards such as SSL (OpenSSL and others) or OpenPGP (GPG, etc.) to do the necessary encryption / decryption. I believe there is library or module support for SSL in both Objective-C (or the iPhone environment) and PHP.
In particular about RC4, it is a stream cipher that is deceptively simple to write, but incredibility easy to mess up in its implementation details. See The Misuse of RC4 in Microsoft Word and Excel, and Can you recommend RC4 128-bit encrypted software? for an well known historic example, and a recommendation of security / cryptography expert (former CTO and co-founder of PGP Corp.).
Added:
The keysize in the php script is based on the raw length of the password data. It also does not use any PKCS7 Padding, so I believe that field should be zero (0) (CCryptor doesn't support padding of stream ciphers, and the php version certainly doesn't use it). In your code CCCrypt used a keysize of 8 bytes (64* bits), whereas I believe you want it to be the length (in bytes) of the password (binary data).
There is no MAC or hash of the data so the functions won't be able to determine valid from invalid decodings.
I think this will get you closer to compatibility with this insecure implementation of RC4 (RC4crypt in PHP).
DES uses 56-bits of key from 64-bits of key input.
Building on #mctylr, Avoid rolling your own whenever possible. If you need RC4, use a pre-built/tested library: OpenSSL RC4. You can replace your entire code with about 3 lines.