我正在开发一个 C# Web api。我添加了一个类库来连接到外部 Web 服务。要登录该资源,请执行以下方法:
/// <summary>
/// Firma mensaje
/// </summary>
/// <param name="messageBytes">Bytes del mensaje</param>
/// <param name="signerCertificate">Certificado usado para firmar</param>
/// <returns>Bytes del mensaje firmado</returns>
/// <remarks></remarks>
public static byte[] SignMessageBytes(byte[] messageBytes, X509Certificate2 signerCertificate)
{
const string ID_FNC = "[FirmaBytesMensaje]";
try
{
// Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
var contentInfo = new ContentInfo(messageBytes);
var signedCms = new SignedCms(contentInfo);
// Creo objeto CmsSigner que tiene las caracteristicas del firmante
var cmsSigner = new CmsSigner(signerCertificate)
{
IncludeOption = X509IncludeOption.EndCertOnly
};
if (VerboseMode) Console.WriteLine(ID_FNC + "***Firmando bytes del mensaje...");
// Firmo el mensaje PKCS #7
signedCms.ComputeSignature(cmsSigner);
if (VerboseMode) Console.WriteLine(ID_FNC + "***OK mensaje firmado");
// Encodeo el mensaje PKCS #7.
return signedCms.Encode();
}
catch (Exception ex)
{
throw new Exception(ID_FNC + "***Error al firmar: " + ex.Message);
}
}
这在本地主机环境中完美运行。但是当我将其发布到 Azure 应用程序服务时,它失败并出现错误:
The system cannot find the file specified.
正在排队
signedCms.ComputeSignature(cmsSigner);
不知道可能是什么原因。如果有人有关于应用程序服务需要的任何额外配置的信息,这对我会有很大帮助。非常感谢!
让 SignMessageBytes 方法在 Azure 环境中工作
尝试更改以下代码:
// Find the certificate by thumbprint
X509Certificate2Collection certs = store.Certificates.Find(
X509FindType.FindByThumbprint,
"your-thumbprint",
false
);
if (certs.Count > 0)
{
X509Certificate2 signerCertificate = certs[0];
// Continue with signing using signerCertificate
}
else
{
throw new Exception("Certificate not found.");
}
将“您的指纹”替换为您证书的实际指纹。