duangan7834 2017-05-10 07:11
浏览 64
已采纳

如何在来自PHP的C#中使用AES加密? [关闭]

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.

  • 写回答

1条回答 默认 最新

  • duan4523 2017-05-10 13:34
    关注

    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))
                        {
    
                                swEncrypt.Write(text);
    
                        }
                    }
    
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据