お世話になります。
C#とPHPの間で暗号化した文字列をやりとりする必要があるのですが、PHP側でどのようにすればよいかよくわからずにいます。
とりあえず、C#とPHPのコードを記載しますので、何かアドバイスをいただけますと幸いです。
C#のコード
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
public class App{
public static void Main(){
var test = new test_crypt.test();
string result = test.Encrypt("abc", "test");
MessageBox.Show(result);
string dresult = test.Decrypt(result, "test");
MessageBox.Show(dresult);
}
}
namespace test_crypt{
public class test{
private Encoding _encode = Encoding.UTF8;
private byte[] _salt = Encoding.UTF8.GetBytes("1234567890");
public string Encrypt(string text, string password){
byte[] bytes = _encode.GetBytes(text);
byte[] inArray = Encrypt(bytes, password);
return Convert.ToBase64String(inArray);
}
private byte[] Encrypt(byte[] strBytes, string password){
SymmetricAlgorithm algorithm = GetAlgorithm();
byte[] key, iv;
GenerateKeyFromPassword(password, algorithm.KeySize, out key, algorithm.BlockSize, out iv);
algorithm.Key = key;
algorithm.IV = iv;
ICryptoTransform cryptoTransform = algorithm.CreateEncryptor();
byte[] result = cryptoTransform.TransformFinalBlock(strBytes, 0, strBytes.Length);
cryptoTransform.Dispose();
return result;
}
public string Decrypt(string text, string password){
byte[] strBytes = Convert.FromBase64String(text);
byte[] bytes = Decrypt(strBytes, password);
return _encode.GetString(bytes);
}
private byte[] Decrypt(byte[] strBytes, string password){
SymmetricAlgorithm algorithm = GetAlgorithm();
byte[] key, iv;
GenerateKeyFromPassword(password, algorithm.KeySize, out key, algorithm.BlockSize, out iv);
algorithm.Key = key;
algorithm.IV = iv;
ICryptoTransform cryptoTransform = null;
try{
cryptoTransform = algorithm.CreateDecryptor();
return cryptoTransform.TransformFinalBlock(strBytes, 0, strBytes.Length);
}
catch (CryptographicException ex){
throw new Exception("復号化に失敗しました。\n" + ex.Message);
}
finally{
cryptoTransform.Dispose();
}
}
protected void GenerateKeyFromPassword(string password, int keySize, out byte[] key, int blockSize, out byte[] iv){
Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, _salt);
rfc2898DeriveBytes.IterationCount = 1;
key = rfc2898DeriveBytes.GetBytes(keySize / 8);
iv = rfc2898DeriveBytes.GetBytes(blockSize / 8);
}
protected virtual SymmetricAlgorithm GetAlgorithm(){
return new AesManaged();
}
}
}
PHPのコード
<?php
$method = 'AES-128-CBC';
$password = 'test';
$plain_text = 'abc';
$salt = '1234567890';
$key_iv = openssl_pbkdf2($password, $salt, 32+16, 1);
$key = substr($key_iv, 0, 32);
$iv = substr($key_iv, 32, 16);
$encrypted_text = openssl_encrypt($plain_text, $method, $key, 0, $iv);
$decrypted_text = openssl_decrypt($encrypted_text, $method, $key, 0, $iv);
echo $encrypted_text."<br>";
echo $decrypted_text."<br>";
?>
以上、よろしくお願いいたします。