2016-03-09 3 views
0

Я хотел бы подписать файл с сертификатом. Я написал следующий код, но я получил «Ошибка содержимого файла», а также я всегда спрашивал секретный ключ. Что я сделал не так? Как я могу отправить закрытый ключ? Спасибо всем.Подпишите файл с X509Certificate2 и личным ключом

 string cSerial = "0C4744041F40B761322124EB691C5F32"; 
     //Find my certificate with serial  
     X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser); 

     my.Open(OpenFlags.ReadOnly); 

     System.Security.Cryptography.RSACryptoServiceProvider csp = null; 

     foreach (X509Certificate2 cert in my.Certificates) 
     { 
      if (cert.SerialNumber.Trim() == cSerial) 
      { csp = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey; } 
     } 
     //Here i have the certificate, it's ok. 
     System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed(); 
     UnicodeEncoding encoding = new UnicodeEncoding(); 
     //////////byte[] data = encoding.GetBytes("test.xml"); 
     byte[] data = File.ReadAllBytes("test.xml") 
     byte[] hash = sha1.ComputeHash(data); 
     byte[] aa = csp.SignHash(hash, System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1")); 
     File.WriteAllBytes("text.p7m", aa); 

     my.Close(); 
+0

UnicodeEncoding.GetBytes не читает файл. Он просто кодирует байты в строке «text.xml» в массив байтов. – Kevin

+0

@Kevin, я редактирую свой источник, но результат не меняется ....... спасибо. – Alexander

+0

Используйте отладчик и узнайте, какая строка создает ошибку. – Kevin

ответ

2

Вы можете решить эту проблему без замка Надувной, только с помощью .NET

/// <summary> 
    ///  Make attached signature. 
    /// </summary> 
    public byte[] SignAttached(X509Certificate2 certificate, byte[] dataToSign) 
    { 
     ContentInfo contentInfo = new ContentInfo(dataToSign); 
     SignedCms cms = new SignedCms(contentInfo, false); 
     CmsSigner signer = new CmsSigner(certificate); 
     cms.ComputeSignature(signer, false); 
     return cms.Encode(); 
    } 

    /// <summary> 
    ///  Make detached signature. 
    /// </summary> 
    public byte[] SignDetached(X509Certificate2 certificate, byte[] dataToSign) 
    { 
     ContentInfo contentInfo = new ContentInfo(dataToSign); 
     SignedCms cms = new SignedCms(contentInfo, true); 
     CmsSigner signer = new CmsSigner(certificate); 
     cms.ComputeSignature(signer, false); 
     return cms.Encode(); 
    } 
+0

Я стараюсь сообщать результаты, спасибо. – Alexander

+0

@ Александр, хорошо. –

+0

Как проверить подпись в прикрепленном и отсоединенном сценарии? –

Смежные вопросы