ichnichtsphp
ichnichtsphp

Reputation: 9

decrypt C# encrypted string in PHP (StringCipher Library)

I want to decrypt a string which i encrypted with c# using the StringCipher Library

what I have tried so far without success:

function decrypt($cipherText, $passPhrase)
{
    $Keysize = 256;
    $DerivationIterations = 1000;
    $cipher_algo = "aes-256-cbc";
    //$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_algo));

    $cipherTextBytesWithSaltAndIv = base64_decode($cipherText);
    $saltStringBytes = substr($cipherTextBytesWithSaltAndIv, 0, ($Keysize / 8));
    $ivStringBytes = substr($cipherTextBytesWithSaltAndIv, ($Keysize / 8), ($Keysize / 8));
    $cipherTextBytes = substr($cipherTextBytesWithSaltAndIv, (($Keysize / 8) * 2), strlen($cipherTextBytesWithSaltAndIv) - (($Keysize / 8) * 2));

    $keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, $DerivationIterations, ($Keysize / 8), true);
    return openssl_decrypt($cipherTextBytes, $cipher_algo, $keyBytes, 0, $ivStringBytes);
}

Upvotes: 0

Views: 170

Answers (1)

ALT4Y
ALT4Y

Reputation: 1

The 128-bit variant in PHP:

<?php

class StringCipher
{
    private const Keysize = 128;
    private const DerivationIterations = 1000;
    private const cipher_algo = "aes-128-cbc";

    public static function Encrypt($plainText, $passPhrase)
    {
        $saltStringBytes = self::Generate128BitsOfRandomEntropy();
        $ivStringBytes = self::Generate128BitsOfRandomEntropy();
        $keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, self::DerivationIterations, (self::Keysize / 8), true);
        $cipherTextBytes = $saltStringBytes . $ivStringBytes . openssl_encrypt($plainText, self::cipher_algo, $keyBytes, OPENSSL_RAW_DATA, $ivStringBytes);
        return base64_encode($cipherTextBytes);
    }

    public static function Decrypt($cipherText, $passPhrase)
    {
        $cipherTextBytesWithSaltAndIv = base64_decode($cipherText);
        $saltStringBytes = substr($cipherTextBytesWithSaltAndIv, 0, (self::Keysize / 8));
        $ivStringBytes = substr($cipherTextBytesWithSaltAndIv, (self::Keysize / 8), (self::Keysize / 8));
        $cipherTextBytes = substr($cipherTextBytesWithSaltAndIv, ((self::Keysize / 8) * 2), strlen($cipherTextBytesWithSaltAndIv) - ((self::Keysize / 8) * 2));
        $keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, self::DerivationIterations, (self::Keysize / 8), true);
        return openssl_decrypt($cipherTextBytes, self::cipher_algo, $keyBytes, OPENSSL_RAW_DATA, $ivStringBytes);
    }

    private static function Generate128BitsOfRandomEntropy()
    {
        return openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::cipher_algo));
    }
}

Upvotes: 0

Related Questions