How to use AES Encryption in C# coming from PHP? [closed]

0 投票
最新提问 用户: (120 分)

We have a project that required us to encrypt data to a 3rd party using PHP's openssl_encrypt function. However, we use C# to develop our apps.

$data = "hello world";
$key = ""very secret key;
base64_encode(openssl_encrypt($data, "aes-256-cbc", $key, OPENSSL_RAW_DATA));

How can the same be achieved in C#?

Thanks in advance.

发表于 用户: (100 分)
You want to know if there is "openssl_encrypt" in C# ?
发表于 用户: (120 分)
Yes. If there's an equivalent function in C# for it.
发表于 用户: (220 分)
So many Google search results for this...
发表于 用户: (100 分)
I dont think theres build in support for that. You'll have to use a libary or write it yourself.


0 投票
最新回答 用户: (240 分)

C# has AES encryption built in.

but before using it you need to go through Decrypt string in C# that was encrypted with PHP openssl_encrypt - since

PHP doesn't even use a key derivation algorithm just takes the bytes of the passphrase and pads it out with zero's

Once you got your iv and key you can use AesManaged and CrytproStream to encrypt the data:

        byte[] iv = null; // get iv form pw
        byte[] key = null; // get key from pw
        using (AesManaged cryptor = new AesManaged())

            ivhex = BitConverter.ToString(iv).Replace("-", string.Empty);
            keyhex = BitConverter.ToString(key).Replace("-", string.Empty);

            // Encrypt File
            using (var ms = new MemoryStream())
                cryptor.Mode = CipherMode.CBC;
                cryptor.Padding = PaddingMode.PKCS7;
                cryptor.KeySize = 256;
                cryptor.BlockSize = 256;

                //We use the random generated iv created by AesManaged
                using (CryptoStream cs = new CryptoStream((Stream)ms, cryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write))
                    using (StreamWriter swEncrypt = new StreamWriter(cs))



                return Convert.ToBase64String(ms.ToArray());
欢迎来到 Security Q&A ,有什么不懂的可以尽管在这里提问,你将会收到社区其他成员的回答。