Finding a way to encrypt messages in C# and decrypting them in PHP or vice versa seems to be a "challenge" for many users. I wrote this tutorial to provide some help with this: below, you can find how to encrypt / decrypt messages in C# / PHP using AES256 with CBC mode.

1.Basic Information

AES 256 with CBC mode requires 3 values: the message, a key (32 bytes long) and an initialization vector (IV). Note that you must use the same IV when encrypting / decrypting a message: otherwise the message is lost. Sending the IV with the message is perfectly safe but it always has to be a random value. Since it has a fixed size, I always place the IV at the end of the encrypted text.

The encrypted messages should be encoded using base64 before being sent.

Encryption steps:

  • encrypt the text
  • add the IV at the end
  • encode everything (base64)

Decryption steps:

  • decode the message
  • get & remove the IV
  • proceed to decypt

Ok, enough talking, let's see some code...

2.PHP Encryption/Decryption Code

PHP accepts keys that are not 32 bytes long and simply extends them to the correct length. Well...C# doesn't, so you'll have to use a key that is 32 bytes long.

Encryption

  1. function encrypt($text, $pkey)
  2. {
  3. $key = $pkey;
  4. $IV = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND);
  5. return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $IV)."-[--IV-[-".$IV);
  6. }

Decryption

  1. function decrypt($text, $pkey)
  2. {
  3. $key = $pkey;
  4. $text = base64_decode($text);
  5. $IV = substr($text, strrpos($text, "-[--IV-[-") + 9);
  6. $text = str_replace("-[--IV-[-".$IV, "", $text);
  7. return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $IV), "\0");
  8. }

3.C# Encryption/Decryption Code

As I said before, C# doesn't accept keys that aren't 32 bytes long - it will throw an error. Also, many people get tricked here because of the encoding (most of the times you have to use Encoding.Default).

Encryption

  1. public static string EncryptMessage(byte[] text, string key)
  2. {
  3. RijndaelManaged aes = new RijndaelManaged();
  4. aes.KeySize = 256;
  5. aes.BlockSize = 256;
  6. aes.Padding = PaddingMode.Zeros;
  7. aes.Mode = CipherMode.CBC;
  8. aes.Key = Encoding.Default.GetBytes(key);
  9. aes.GenerateIV();
  10. string IV = ("-[--IV-[-" + Encoding.Default.GetString(aes.IV));
  11. ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
  12. byte[] buffer = text;
  13. return
  14. Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV));
  15. }

Decryption

    1. public static string DecryptMessage(string text, string key)
    2. {
    3. RijndaelManaged aes = new RijndaelManaged();
    4. aes.KeySize = 256;
    5. aes.BlockSize = 256;
    6. aes.Padding = PaddingMode.Zeros;
    7. aes.Mode = CipherMode.CBC;
    8. aes.Key = Encoding.Default.GetBytes(key);
    9. text = Encoding.Default.GetString(Convert.FromBase64String(text));
    10. string IV = text;
    11. IV = IV.Substring(IV.IndexOf("-[--IV-[-") + 9);
    12. text = text.Replace("-[--IV-[-" + IV, "");
    13. text = Convert.ToBase64String(Encoding.Default.GetBytes(text));
    14. aes.IV = Encoding.Default.GetBytes(IV);
    15. ICryptoTransform AESDecrypt = aes.CreateDecryptor(aes.Key, aes.IV);
    16. byte[] buffer = Convert.FromBase64String(text);
    17. return Encoding.Default.GetString(AESDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
    18. }

C#/PHP Compatible Encryption (AES256) ZZ的更多相关文章

  1. 提供openssl -aes-256-cbc兼容加密/解密的简单python函数

    原文链接:http://joelinoff.com/blog/?p=885 这里的示例显示了如何使用python以与openssl aes-256-cbc完全兼容的方式加密和解密数据.它是基于我在本网 ...

  2. [转载] TLS协议分析 与 现代加密通信协议设计

    https://blog.helong.info/blog/2015/09/06/tls-protocol-analysis-and-crypto-protocol-design/?from=time ...

  3. Lync 2013安装中遇到的关于SQL Mirroring的一次报错的解决

    Problem Description ================= Following the Lync Deployment Wizard to setup Database Mirrori ...

  4. vyos User Guide

    vyos User Guide 来源 https://wiki.vyos.net/wiki/User_Guide The VyOS User Guide is focused on providing ...

  5. TLS协议分析

    TLS协议分析 本文目标: 学习鉴赏TLS协议的设计,透彻理解原理和重点细节 跟进一下密码学应用领域的历史和进展 整理现代加密通信协议设计的一般思路 本文有门槛,读者需要对现代密码学有清晰而系统的理解 ...

  6. Corosync 配置描述

    NAME corosync.conf - corosync executive configuration file SYNOPSIS /etc/corosync/corosync.conf DESC ...

  7. Cisco asa组建IPSEC for ikev1

    IPSec的实现主要由两个阶段来完成:--第一阶段,双方协商安全连接,建立一个已通过身份鉴别和安全保护的通道.--第二阶段,安全协议用于保护数据的和信息的交换. IPSec有两个安全协议:AH和ESP ...

  8. 设置 cipher suite

    https://man.openbsd.org/SSL_CTX_set_cipher_list.3#ECDHE SSL_CTX_set_cipher_list() sets the list of a ...

  9. 【原创】大叔经验分享(41)hdfs开启kerberos之后报错Encryption type AES256 CTS mode with HMAC SHA1-96 is not supported/enabled

    hdfs开启kerberos之后,namenode报错,连不上journalnode 2019-03-15 18:54:46,504 WARN org.apache.hadoop.security.U ...

随机推荐

  1. windows下ipython的tab补全,只需安装pyreadline即可.

    运行ipython提示缺失模块 在windows下安装readline失败. 根据提示访问 https://urllib3.readthedocs.org/en/latest/security.htm ...

  2. 在Windows下用gSoap实现简单加法实例

    实现一个简单的a+b程序,在服务器端写一个程序,里面包含了a+b的函数,然后通过客户端代码向其发送两个数字,在服务器运算得到结果返回给客户端显示出来. 1.在gSoap的官网上下载文件夹,本人的版本是 ...

  3. compass sprite

    1.compass init 初始化一个compass项目,并创建一个images文件夹用来存放合成的sprite图 2.将切好的小图放到images文件夹中 3.在sass文件夹中新建一个test. ...

  4. HTML5 的绘图支持- canvas

    Canvas HTML5新增了一个canvas元素,它是一张空画布,开发者需要通过JavaScript脚本进行绘制. 在canvas上绘图,经过如下3步 (1) 获取canvas元素对应的DOM对象. ...

  5. 【 java版坦克大战--事件处理】 让坦克动起来--事件处理的准备

    要能够控制坦克运动,必须用到事件处理的知识. 事件处理的一个demo. /** * 事件处理机制:委派事件模型.指当事件发生的时候,产生事件的对象(事件源),会把此 * "消息"传 ...

  6. 查看文章 mysql:表注释和字段注释[转]

    1 创建表的时候写注释 create table test1 ( field_name int comment '字段的注释' )comment='表的注释'; 2 修改表的注释 alter tabl ...

  7. STM32内存映射

    一.概述 STM32内存映射是STM32的架构的重要组成部分,不可或缺. 二.STM32内存映射图 1.内存映射图--摘自<CM3权威指南> 2.内存映射图--摘自<STM32F10 ...

  8. android SurfaceView绘制 重新学习--控制动画移动

    直接上demo,图是自己切的,将就用吧.点击左右两边分别向左右移动. public class MySurfaceView extends SurfaceView implements Callbac ...

  9. skiplist 跳表(1)

    最近学习中遇到一种新的数据结构,很实用,搬过来学习. 原文地址:skiplist 跳表   为什么选择跳表 目前经常使用的平衡数据结构有:B树,红黑树,AVL树,Splay Tree, Treep等. ...

  10. 第 17 章 责任链模式【Chain of Responsibility Pattern】

    以下内容出自:<<24种设计模式介绍与6大设计原则>> 中国古代对妇女制定了“三从四德”的道德规范,“三从”是指“未嫁从父.既嫁从夫.夫死从子”,也就是说一个女性,在没有结婚的 ...