- Привет всем!
- У меня возникли проблемы с преобразованием кода с C# на PHP.
- Мне нужен код на php, чтобы использовать тот же алгоритм, что и мой код на c#.
- Подпись в созданном мной коде C# была проверена правильно, но подпись, созданная на основе кода php (я использовал тот же закрытый ключ) не был проверен.
private void btn_Create_Signature_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txt_CRB_3_3_x.Text))
{
MessageBox.Show("ID is not entered.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string crbKeyFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "crb.xml");
string crbxml = File.ReadAllText(crbKeyFilePath);
string textBoxData = txt_CRB_3_3_x.Text; // Data from textbox1
string idTagStart = "";
string idTagEnd = "";
int startIndex = crbxml.IndexOf(idTagStart) + idTagStart.Length;
int endIndex = crbxml.IndexOf(idTagEnd);
if (startIndex >= 0 && endIndex >= 0)
{
string updatedCrbxml = crbxml.Substring(0, startIndex) + textBoxData + crbxml.Substring(endIndex);
File.WriteAllText(crbKeyFilePath, updatedCrbxml);
}
else
{
MessageBox.Show("ID tags not found in the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Path to the file to store the signature
string signedFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "crb.key");
// Read XML content from the file
XElement xelement = XElement.Load(crbKeyFilePath);
// Display XML content in a message box
MessageBox.Show(xelement.ToString(), "XML Content");
// String containing the encrypted private key and password
string privateKey = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "privateKey.pem");
string fileContent = File.ReadAllText(privateKey);
string string_2 = "999999999";
// Remove header and footer from the PEM string
string base64PrivateKey = ExtractBase64FromPem(fileContent);
// Create or get the Signature element
XElement signatureElement = xelement.Element("Signature") ?? new XElement("Signature");
try
{
if (signatureElement.Parent != null)
{
signatureElement.Remove();
}
// Decrypt the private key
AsymmetricKeyParameter asymmetricKeyParameter = smethod_1(base64PrivateKey, string_2);
// Prepare data for signing
byte[] bytes = Encoding.UTF8.GetBytes(xelement.ToString(SaveOptions.DisableFormatting));
// Initialize the signer with the signature algorithm
string string_0 = "1.2.840.10045.4.3.4"; // Change the algorithm if needed
ISigner signer = SignerUtilities.GetSigner(string_0);
signer.Init(true, asymmetricKeyParameter);
signer.BlockUpdate(bytes, 0, bytes.Length);
// Create the signature
byte[] signature = signer.GenerateSignature();
signatureElement.Value = Convert.ToBase64String(signature);
// Save the signature to a file
string signatureBase64 = Convert.ToBase64String(signature);
File.WriteAllText("signatureCSharp.txt", signatureBase64);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while creating the signature: " + ex.Message);
return;
}
finally
{
// Add the Signature element to the XML
xelement.Add(signatureElement);
// Convert the XML content to a byte array
byte[] xmlBytes = Encoding.UTF8.GetBytes(xelement.ToString());
// Encode the byte array to Base64 string
string base64EncodedXML = Convert.ToBase64String(xmlBytes);
// Save the Base64 string to a file
File.WriteAllText(signedFilePath, base64EncodedXML);
MessageBox.Show("Signature created and saved to file: " + signedFilePath, "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
-
Исходный код PHP и закрытый ключ:
- Это содержимое XML-файла, который необходимо подписать:
Standard
Alessandro Maciell
[email protected]
MEUCIQDPSHurS8VlCXGKKvQrMlKOlvRbg0t5+J3O64XYNawqJQIgXrvJjIk0e7ZFt4Kqhosz4tTBQOJ3H3Z+0xatZ0P7ir4=
- Исходный код C# проверяет подпись:
{
// Determine the path to the crb.key file in the application's root directory
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "crb.key");
// Check if the file exists
if (!File.Exists(filePath))
{
Console.WriteLine("File crb.key does not exist.");
return;
}
string string_1 = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEnO2SV+sdiMX9OzjcWrsDDlWR7AGfh9fNQgnE2AB/QdEYP0AmAjVPGTORSRlSNF9R6V4rPqSJDZRuEcNqOYmBmA==";
// Read XML content from the crb.key file
XElement xelement = XElement.Load(filePath);
XElement signatureElement = xelement.Element("Signature");
bool flag = false;
if (signatureElement != null)
{
try
{
signatureElement.Remove(); // Temporarily remove the "Signature" element
AsymmetricKeyParameter asymmetricKeyParameter = smethod_3(string_1);
byte[] bytes = Encoding.UTF8.GetBytes(xelement.ToString(SaveOptions.DisableFormatting));
ISigner signer = SignerUtilities.GetSigner(this.string_0);
signer.Init(false, asymmetricKeyParameter);
signer.BlockUpdate(bytes, 0, bytes.Length);
flag = signer.VerifySignature(Convert.FromBase64String(signatureElement.Value));
}
finally
{
xelement.Add(signatureElement); // Add the "Signature" element back
}
}
// Use the flag variable to perform necessary actions after verifying the signature
if (flag)
{
// Valid signature
MessageBox.Show("Valid signature.");
}
else
{
// Invalid signature
MessageBox.Show("Invalid signature.");
}
}
private string ExtractBase64FromPem(string pemContent)
{
var start = "-----BEGIN EC PRIVATE KEY-----";
var end = "-----END EC PRIVATE KEY-----";
var base64 = pemContent
.Replace(start, "")
.Replace(end, "")
.Replace("\r", "")
.Replace("\n", "")
.Trim();
return base64;
}
Подробнее здесь: https://stackoverflow.com/questions/784 ... c-sharp-to