I need to convert the following php code in C#:
$res = mac256($ent, $key);
$result = encodeBase64($res);
where
function enc
Redsys provides libraries for php and java.
Starting from the java library, I've translated the ApiMacSha256 class to C#
public class ApiMacSha256 {
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////// FUNCIONES AUXILIARES: ///////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
/** 3DES Function */
private byte[] encrypt_3DES(byte[] key, string data) {
//http://www.mywebexperiences.com/2012/12/11/crypting-data-using-3des-c/
//http://stackoverflow.com/a/33479952/2938518
using (var tdes = new TripleDESCryptoServiceProvider()) {
tdes.IV = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
tdes.Key = key;
tdes.Padding = PaddingMode.Zeros;
tdes.Mode = CipherMode.CBC;
var toEncrypt = Encoding.ASCII.GetBytes(data);
var result = tdes.CreateEncryptor().TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
return result;
}
}
/** MAC Function */
private byte[] mac256(string dsMerchantParameters, byte[] secretKo) {
//http://stackoverflow.com/a/17315619/2938518
byte[] hash;
using (var hmac = new HMACSHA256(secretKo)) {
hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(dsMerchantParameters));
}
return hash;
}
/** Base64 Functions */
private string encodeB64String(byte[] data) {
return Convert.ToBase64String(data, Base64FormattingOptions.None);
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////// FUNCIONES PARA LA GENERACIÓN DEL FORMULARIO DE PAGO: ////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
public String createMerchantSignature(string merchantParamsB64, string claveComercio, string OrderId) {
byte[] clave = Convert.FromBase64String(claveComercio);
byte[] secretKo = encrypt_3DES(clave, OrderId);
// Se hace el MAC con la clave de la operación "Ko" y se codifica en BASE64
byte[] hash = mac256(merchantParamsB64, secretKo);
String res = encodeB64String(hash);
return res;
}
}
The main method 'createMerchantSignature', requires a string encoded in base64 of the merchant params embeded in a json structure, the secret key of the merchant and the OrderId.