PHP implementation of RNCryptor

Overview

RNCryptor PHP

Build Status

This implementation strives to be fully compatible with Rob Napier's Objective-C implementation of RNCryptor. It supports both encryption and decryption of all RNCryptor schema versions through version 3. Due to security concerns with schemas 0 through 2, it is strongly recommended to use schema 3 wherever possible. This is the default if none is specified.

Basic usage is seen in the examples folder.

Installation

This library assumes you are using Composer for dependency management.

composer require rncryptor/rncryptor

If your project itself does not use Composer, then it's about time that it did. ;-) We strongly urge using it. Otherwise you will have to manually read composer.json and make sure the named dependencies are properly loaded into your project.

FAQ

It's complaining about a missing function called hash_pbkdf2

This error almost certainly means that this project's dependencies are not installed or being autoloaded properly. See the Installation section above for more.

It won't decrypt. The "+" on the sending end is getting turned into a " " on the receiving end.

This is usually due to passing an encrypted string into an HTTP request without taking care to encode it for HTTP first. It's because Base64 (which RNCryptor's encrypted strings are encoded in) sometimes includes the "+" character in its output, but this character has special meaning in HTTP encoding.

You can most likely solve this by passing the encrypted string through rawurlencode() on the sending end (or whatever is the equivalent for the language you are working with) before passing it into your HTTP request. And on the receiving end, you might need to use rawurldecode() on the string if your framework isn't already doing this for you.

Comments
  • Encrypt with PHP and decrypt on iPhone problem

    Encrypt with PHP and decrypt on iPhone problem

    I encrypt a string with secrect key on server (PHP)

    public static function Encrypt($string, $password) { require LIBS . '/RNCryptor/autoload.php';

        $cryptor = new \RNCryptor\Encryptor();
        return $cryptor->encrypt($string, $password);
    }
    

    and try to decrypt it on iPhone

    NSData* encryptedData = [@"AwH3lRq1dHsdyjsWzYmBpIVQSHkdjvGbOXLbCW1r240ZFIgFXgCj" dataUsingEncoding:NSUTF8StringEncoding]; NSData *decryptedData = [RNDecryptor decryptData:encryptedData withPassword:@"123456" error:&error]; //convert decryptedData to decryptedString but it is an empty string

    Help me fix that please !

    Thanks !

    opened by anhhtz 16
  • Unsupported schema version 5 when decrypt encrypted string

    Unsupported schema version 5 when decrypt encrypted string

    Hello, I have an encrypted string like this: BQPafXL85Mc01lu9cyWthMxlwdi7uYXdE/jlbNo7LAJZBdKBhw9gdejwgSEJAJFUjjykSdYMmMnE9gUZdlpiHh6u6MJ/mXy3tRjOdwTfsq87dxCck+QCob6ZRPlC0Ysv3uvCSDIeNv8/imR7KOXbxTYh8cZzHm36ZBR4ivH91+iiLBdnmH7flP/zHBY/12CoTZ2A

    But when i put to decrypt function the code warning to me this error: Exception: Unsupported schema version 5 in D:\Hosting_Local\wamp\www\test\lib\RNCryptor\Cryptor.php on line 70 When i check line 70 on Cryptor.php i saw that the code just have 0 -> 3 version of encryption. So why do the hash return version 5? further more i notice that the encrypted hash will have some format like this: AW + [the rest of encrypted hash] But in the hash client sent to me i see the format has changed to: BQ + [the rest of encrypted hash] Do i have some way to know which version or config that the client used to encrypt this? it's kinda weird to normal hash of RNCryptor which i am using so i don't know how to decrypt this hash to orginal source.

    opened by karmamaster 9
  • Function mcrypt_create_iv() is deprecated in PHP 7.1

    Function mcrypt_create_iv() is deprecated in PHP 7.1

    Function mcrypt_create_iv() is deprecated in PHP 7.1 File: /lib/RNCryptor/Encryptor.php Line: 114

    Function mcrypt_encrypt() is deprecated in PHP 7.1 File: /lib/RNCryptor/Encryptor.php Line: 82

    opened by sicaboy 6
  • Cryptor.php with PHP 5.3.13

    Cryptor.php with PHP 5.3.13

    Hi

    The server where I try RNCryptor (latest version of both iOS and php) work with PHP 5.3.13. The function hash_pbkdf2 called in cryptor.php doesn't exist so I replaced the line

    	return hash_pbkdf2($this->_settings->pbkdf2->prf, $password, $salt, $this->_settings->pbkdf2->iterations, $this->_settings->pbkdf2->keyLength, true);
    

    with a class found in php.net. Then I changed the function _generateKey as follow

    public function _generateKey($salt, $password) {

    	if ($this->_settings->truncatesMultibytePasswords) {
    		$utf8Length = mb_strlen($password, 'utf-8');
    		$password = substr($password, 0, $utf8Length);
    	}
    
    	$hash =  $this->hash_pbkdf2($this->_settings->pbkdf2->prf, $password, $salt, $this->_settings->pbkdf2->iterations, $this->_settings->pbkdf2->keyLength, true);
        return $hash;
    }
    

    introducing the function

    public function hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) { $data = array('algorithm' => $algorithm, 'password' => $password, 'salt' => $salt, 'count' => $count, 'key_length' => $key_length, 'raw_output' => $raw_output); try { $pbkdf2 = new pbkdf2($data); return $pbkdf2->hash(); } catch (Exception $e) { throw $e; } }

    and the class

        class pbkdf2  extends Cryptor {
            public $algorithm;
            public $password;
            public $salt;
            public $count;
            public $key_length;
            public $raw_output;
    
            private $hash_length;
            private $output         = "";
    
            public function __construct($data = null)
            {
                if ($data != null) {
                    $this->init($data);
                }
            }
    
            public function init($data)
            {
                $this->algorithm  = $data["algorithm"];
                $this->password   = $data["password"];
                $this->salt       = $data["salt"];
                $this->count      = $data["count"];
                $this->key_length = $data["key_length"];
                $this->raw_output = $data["raw_output"];
            }
    
            public function hash()
            {
                $this->algorithm = strtolower($this->algorithm);
                if(!in_array($this->algorithm, hash_algos(), true))
                    throw new Exception('PBKDF2 ERROR: Invalid hash algorithm.');
    
                if($this->count <= 0 || $this->key_length <= 0)
                    throw new Exception('PBKDF2 ERROR: Invalid parameters.');
    
                $this->hash_length = strlen(hash($this->algorithm, "", true));
                $block_count = ceil($this->key_length / $this->hash_length);
                for ($i = 1; $i <= $block_count; $i++) {
                    // $i encoded as 4 bytes, big endian.
                    $last = $this->salt . pack("N", $i);
                    // first iteration
                    $last = $xorsum = hash_hmac($this->algorithm, $last, $this->password, true);
                    // perform the other $this->count - 1 iterations
                    for ($j = 1; $j < $this->count; $j++) {
                        $xorsum ^= ($last = hash_hmac($this->algorithm, $last, $this->password, true));
                    }
                    $this->output .= $xorsum;
                    if($this->raw_output)
                        return substr($this->output, 0, $this->key_length);
                    else
                        return bin2hex(substr($this->output, 0, $this->key_length));
                }
            }
    
    	}
    

    found in php.net.

    I have a problem decrypting a string generated by a simple iOS app, transmitted to a simple php module on the server that only GET the crypted string and try to decrypting it (null string returned), the question is:

    may these changes in cryptor.php module could compromise the decrypting process?

    Thanks in advance Marino

    opened by marinoCr 4
  • Using Key to Encrypt and Decrypt data

    Using Key to Encrypt and Decrypt data

    Hello fellow developers,

    I was looking for ways of optimizing and reducing encryption/decryption time...

    From the examples I can see that I need to encrypt / decrypt data using 'plain text password' and Library generates key from that 'plain text password'...

    Is there any possibilities that I could use that generated KEY straight away without loosing time on its generation?

    Thanks in advance.

    opened by JavaMachine 4
  • How do I convert C# Rijndael encryption to PHP

    How do I convert C# Rijndael encryption to PHP

    I'm trying to encrypt and decrypt data between client (C#) and server PHP.

    i don't understand encryption enough to work out

    so i need to convert C# to php thanks

    Any help is appreciated.

    here is my code: C#:

    private static readonly string PasswordHash = "P@@Sw0rd"; private static readonly string SaltKey = "S@LT&KEY"; private static readonly string VIKey = "@1B2c3D4e5F6g7H8";

        static void Main(string[] args)
        {
      
            string message = "test@123";
    
         
            string encrypted = Encrypt(message);
    
            string DecryptString = encrypted;
            string decrypted = Decrypt(DecryptString);
            Console.WriteLine(encrypted);
    
    
        }
        
    
        public static string Encrypt(string plainText)
        {
            byte[] bytes1 = Encoding.UTF8.GetBytes(plainText);
            byte[] bytes2 = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(32);
    
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Mode = CipherMode.CBC;
            rijndaelManaged.Padding = PaddingMode.Zeros;
            ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(bytes2, Encoding.ASCII.GetBytes(VIKey));
            byte[] array;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(bytes1, 0, bytes1.Length);
                    cryptoStream.FlushFinalBlock();
                    array = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(array);
        }
    
        public static string Decrypt(string encryptedText)
        {
            byte[] buffer = Convert.FromBase64String(encryptedText);
            byte[] bytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(32);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Mode = CipherMode.CBC;
            rijndaelManaged.Padding = PaddingMode.None;
            ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(bytes, Encoding.ASCII.GetBytes(VIKey));
            MemoryStream memoryStream = new MemoryStream(buffer);
            CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] numArray = new byte[buffer.Length];
            int count = cryptoStream.Read(numArray, 0, numArray.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(numArray, 0, count).TrimEnd("\0".ToCharArray());
        }
    

    }

    opened by baaslaawe 3
  • Issues Decrypting Image File from Android to PHP

    Issues Decrypting Image File from Android to PHP

    I encrypt an image file on Android, and then upload it to the server. In PHP, I try to decrypt, but it keeps getting errors. Sometimes base64_decode returns nothing, sometimes I get Fatal error: Uncaught exception 'Exception' with message 'Unsupported schema version 23' in Cryptor.php.

    Android:

                File file = new File(Environment.getExternalStorageDirectory()
                        .getPath() + "/" + filename);
    
                byte[] originalBytes = FileUtils.readFileToByteArray(file);
                byte[] encryptedBytes = new AES256JNCryptor().encryptData(originalBytes, "test".toCharArray());
    
                FileUtils.writeByteArrayToFile(file, encryptedBytes);
    

    PHP: $string = file_get_contents($file); $decryptor = new \RNCryptor\Decryptor(); $decryptedData` = $decryptor->decrypt($string, "test");

    opened by shevyshapiro 3
  • Update Cryptor.php

    Update Cryptor.php

    I think is better uses pbkdf2 function because hash_pbkdf2 is only in php 5.5 and later and this other function can work in 5.3 and 5.4... Saludos desde Mexico!!!

    opened by raulsilvamx 3
  • Encrypt with objc decrypt PHP problem

    Encrypt with objc decrypt PHP problem

    Hi, ObjC side encryption: (Using RNCryptor (3.0.1))

    NSData *data = [@"TEST STRING" dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSData *encryptedData = [RNEncryptor encryptData:data
                                        withSettings:kRNCryptorAES256Settings
                                            password:@"myPassword"
                                               error:&error];
    if (error == nil) {
        NSString* output = [encryptedData base64EncodedStringWithOptions:0];
    }
    

    PHP side decryption: (rncryptor/rncryptor 3.1.4 on Windows + PHP5.4.45 + mcrypt 2.5.8)

    $decryptor = new \RNCryptor\Decryptor;
    $password = "myPassword";
    $base64Encrypted = "AwEpke5sjJK7vtz3Nt4BuJg8/BU03AiguUkl7BlYXOyY8A1MqyOwH5BRub+XBiPZDVWeYZ512XVU/wkL/J+d72NzQeSc4NFri5aAk0hCGbgpbA==";
    echo "Base64 Encrypted:\n$base64Encrypted\n\n";
    $decrypted = $decryptor->decrypt($base64Encrypted, $password);
    echo "Plaintext:\n$decrypted\n\n";
    

    If I do the encrypt/decrypt on the same side or I do the decryption in PHP CLI (5.6) on my mac it works fine. Do you know any issue what could cause this?

    Regards, Imre

    opened by imrepapp 2
  • Class 'RNCryptor\RNCryptor\Encryptor' not found

    Class 'RNCryptor\RNCryptor\Encryptor' not found

    Hello

    Thank you so much for the great effort. I seem to have a problem with accessing the functionality of this library. I am new to Composer and I seem to have a problem with understanding wich "autoloader.php" to require in the code. I am simply using the supplied "encrypt.php" example and getting the "Class 'RNCryptor\RNCryptor\Encryptor' not found " no matter which autoloader I try to require.

    I am working on a shared hosting server where my composer got installed in .php and "vendor" got installed in the application user directory "~/" next to ".php".

    I am thinking my problem is not requiring the correct autoloader.php and/or instantiating the correct classpath 'RNCryptor\RNCryptor\Encryptor'.

    I hope you can help me with this pit hole

    Baher

    opened by BaherHosni 2
Owner
AES file format with implementations in many languages.
null
Php-rpc-server - JSON RPC server implementation for PHP.

JSON RPC Server implementation for PHP. The json-rpc is a very simple protocol. You can see this by reading the protocol specification. This library i

null 4 Sep 28, 2022
A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

Felix Becker 1.1k Jan 4, 2023
PHP implementation of circuit breaker pattern.

What is php-circuit-breaker A component helping you gracefully handle outages and timeouts of external services (usually remote, 3rd party services).

ArturEjsmont 169 Jul 28, 2022
Implementation of the Token Bucket algorithm in PHP.

Token Bucket This is a threadsafe implementation of the Token Bucket algorithm in PHP. You can use a token bucket to limit an usage rate for a resourc

null 477 Jan 7, 2023
A PHP implementation of the Unleash protocol aka Feature Flags in GitLab.

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab. This implementation conforms to the official Unleash standards and implement

Dominik Chrástecký 2 Aug 18, 2021
An implementation of the Minecraft: Bedrock Edition protocol in PHP

BedrockProtocol An implementation of the Minecraft: Bedrock Edition protocol in PHP This library implements all of the packets in the Minecraft: Bedro

PMMP 94 Jan 6, 2023
PHP Implementation of PASERK

PASERK (PHP) Platform Agnostic SERialized Keys. Requires PHP 7.1 or newer. PASERK Specification The PASERK Specification can be found in this reposito

Paragon Initiative Enterprises 9 Nov 22, 2022
A minimalistic implementation of Promises for PHP

libPromise A minimalistic implementation of Promises for PHP. Installation via DEVirion Install the DEVirion plugin and start your server. This will c

null 8 Sep 27, 2022
PHP's Promse implementation depends on the Swoole module.

php-promise-swoole PHP's Promse implementation depends on the Swoole module. Promise::allsettled([ /** Timer 调用 */ /** Timer call */

拓荒者 3 Mar 15, 2022
A circular buffer implementation in PHP

Circular Buffer Installation ?? This is a great place for showing how to install the package, see below: Run $ composer require lctrs/circular-buffer

null 1 Jan 11, 2022
This package contains a PHP implementation to solve 3D bin packing problems.

3D Bin Packager This package contains a PHP implementation to solve 3d bin packing problems based on gedex implementation on Go and enzoruiz implement

Farista Latuconsina 7 Nov 21, 2022
PHP implementation for reading and writing Apache Parquet files/streams

php-parquet This is the first parquet file format reader/writer implementation in PHP, based on the Thrift sources provided by the Apache Foundation.

null 17 Oct 25, 2022
PHP implementation of PSON

PSON-PHP Information This library is an php implementation of PSON. This software is licensed under the MIT License. Installation You can install this

Simplito 1 Sep 29, 2019
An open-source Minecraft: Java Edition server implementation, written in PHP.

PHPCraft An open-source Minecraft: Java Edition server implementation, written in PHP. What is PHPCraft? PHPCraft is an open-source Minecraft: Java Ed

Karen/あけみ 17 Dec 31, 2022
Php-file-iterator - FilterIterator implementation that filters files based on a list of suffixes, prefixes, and other exclusion criteria.

php-file-iterator Installation You can add this library as a local, per-project dependency to your project using Composer: composer require phpunit/ph

Sebastian Bergmann 7.1k Jan 3, 2023
phly-mustache is a Mustache implementation written for PHP

phly-mustache is a Mustache implementation written for PHP. It conforms to the principles of mustache, and allows for extension of the format via pragmas.

phly 16 Oct 13, 2021
This is a JSONPath implementation for PHP based on Stefan Goessner's JSONPath script.

JSONPath for PHP This is a JSONPath implementation for PHP based on Stefan Goessner's JSONPath script. JSONPath is an XPath-like expression language f

Sascha Greuel 100 Dec 30, 2022
Swaggest JSON-schema implementation for PHP

Swaggest JSON-schema implementation for PHP High definition PHP structures with JSON-schema based validation. Supported schemas: JSON Schema Draft 7 J

null 370 Dec 29, 2022
This repository demonstrates exemplary implementation of chat using HTTP and Websocket servers in PHP using Kraken Framework components.

This repository demonstrates exemplary implementation of chat using HTTP and Websocket servers in PHP using Kraken Framework components.

Kraken 48 Aug 11, 2021