2011-07-05 3 views
11

다음 질문 및 답변에 StackOverflow 적절한 암호없이 열 수없는 PDF를 생성하는 방법을 보여줍니다.iTextSharp 비밀 번호로 보호 된 PDF

Password protected PDF using C#

내가 마찬가지로이 프레임 워크를 사용하고 싶지만, 약간 변경된 내 사용자가 암호를 필요없이 PDF를 "열기"할 수 있습니다,하지만 그들은 암호가 있다면 그들에게 PDF를 편집 할 수 있도록.

iTextSharp로 가능합니까?

이 문제가 발생하면 WF 4.0 사용자 지정 활동 내에서 C# 4.0으로 작업하고 있습니다.

+1

아니, 그것은 정말 중요하지 않습니다. iTextSharp 클래스 중 아파트 모델에 민감한 경우 Activity를 실행하는 동안 스레딩을 제어해야 할 수도 있습니다. – Will

답변

24

예, PdfEncryptor.Encrypt(), userPasswordownerPassword에 전달할 수있는 두 개의 암호가 있습니다. null을 에 전달하면 사람들이 비밀번호를 지정하지 않고도 열 수 있습니다.

 string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
     string InputFile = Path.Combine(WorkingFolder, "Test.pdf"); 
     string OutputFile = Path.Combine(WorkingFolder, "Test_enc.pdf"); 

     using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)) 
      { 
       PdfReader reader = new PdfReader(input); 
       PdfEncryptor.Encrypt(reader, output, true, null, "secret", PdfWriter.ALLOW_SCREENREADERS); 
      } 
     } 
+0

감사합니다. 나는 이것을 지금 시험 할 것이다. –

0

또 다른 구현 :

public static void Common_PassWordProtectPDF_Static_WithoutEmail(FileInfo[] filteredfiles, string strAgentName, string strAgentCode, string strpassword, string strEmailID, string sourcefolder, string strdestfolder, string strdestinationFileName) 
{ 
    foreach (FileInfo file in filteredfiles) 
    { 
     //string sourcePdf = Convert.ToString(ConfigurationManager.AppSettings["SourceFolder"]) + "\\" + file.Name; 
     //string strdestPdf = Convert.ToString(ConfigurationManager.AppSettings["DestinationFolder"]) + file.Name; 

    string sourcePdf = sourcefolder + "\\" + file.Name; 
    string strdestPdf = strdestfolder + strdestinationFileName; 

    using (Stream input = new FileStream(sourcePdf, FileMode.Open, FileAccess.Read, FileShare.Read)) 
    { 
     //sourcePdf unsecured PDF file 
     //destPdf secured PDF file 

     using (Stream output = new FileStream(strdestPdf, FileMode.Create, FileAccess.Write, FileShare.None)) 
     { 
      PdfReader pdfReader = new PdfReader(input); 
      X509Store store = new X509Store("My"); 
      store.Open(OpenFlags.ReadOnly); 

      X509Certificate2 cert = new X509Certificate2(); 
      RSACryptoServiceProvider csp = null; 
      AcroFields fields = pdfReader.AcroFields; 

      foreach (X509Certificate2 mCert in store.Certificates) 
      { 
       //TODO's 
       string strresult = mCert.GetName(); 
       bool str123 = false; 
       if (strresult.Contains("Certificate name") == true) 
       { 
        csp = (RSACryptoServiceProvider)mCert.PrivateKey; 

        SHA1Managed sha1 = new SHA1Managed(); 
        UnicodeEncoding encoding = new UnicodeEncoding(); 
        byte[] data = encoding.GetBytes(file.Name); 
        byte[] hash = sha1.ComputeHash(data); 

        // Sign the hash 

        byte[] signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); 

        if (Verify(file.Name, signature, mCert)) 
        { 
         char s = pdfReader.PdfVersion; 
         //var pdfStamper = PdfStamper.(pdfReader, output, s, @"\0", true); 
         //csp.SignData(signature, true); 
         pdfReader.Appendable = false; 

         Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); 
         Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { 
    cp.ReadCertificate(mCert.RawData)}; 

         IExternalSignature externalSignature = new X509Certificate2Signature(mCert, "SHA-1"); 


         // var signedPdf = new FileStream(output, FileMode.Create); 
         // var signedPdf = PdfEncryptor.Encrypt(pdfReader, output, true, strpassword, strpassword, PdfWriter.ALLOW_PRINTING); 
         //char s = pdfReader.PdfVersion; 
         var pdfStamper = PdfStamper.CreateSignature(pdfReader, output, s, @"\", false); 
         PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; 

         byte[] USER = Encoding.ASCII.GetBytes("userpwd"); 
         byte[] OWNER = Encoding.ASCII.GetBytes(strpassword); 

         Rectangle cropBox = pdfReader.GetCropBox(1); 
         float width = 108; 
         float height = 32; 

         // signatureAppearance.SignatureGraphic = Image.GetInstance("C:\\logo.png"); 
         //signatureAppearance.Layer4Text = "document certified by"; 
         //signatureAppearance.Reason = "Because I can"; 
         //signatureAppearance.Location = "My location"; 
         //signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature"); 

         Rectangle rect = new Rectangle(600, 100, 300, 150); 
         Chunk c = new Chunk("A chunk represents an isolated string. "); 
         rect.Chunks.Add(c); 
         //signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 600, 150), pdfReader.NumberOfPages, "Signature"); 

         signatureAppearance.SetVisibleSignature(rect, pdfReader.NumberOfPages, "Signature"); 

         // signatureAppearance.SetVisibleSignature(new Rectangle(cropBox.GetLeft(0), cropBox.GetBottom(0), cropBox.GetLeft(width), cropBox.GetLeft(height)), pdfReader.NumberOfPages, "Signature"); 

         signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; 
         pdfStamper.SetEncryption(USER, OWNER, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128); 
         MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); 

         pdfStamper.Close(); 


         // PdfEncryptor.Encrypt(pdfReader, output, true, strpassword, strpassword, PdfWriter.SIGNATURE_EXISTS); 
        } 
        else 
        { 
         Console.WriteLine("ERROR: Signature not valid!"); 
        } 
       } 
      } 

      string Password = strpassword; 

     } 
    } 
} 




public static byte[] Sign(string text, string certSubject) 
{ 

    // Access Personal (MY) certificate store of current user 

    X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser); 

    my.Open(OpenFlags.ReadOnly); 

    // Find the certificate we’ll use to sign 

    RSACryptoServiceProvider csp = null; 

    foreach (X509Certificate2 cert in my.Certificates) 
    { 

     if (cert.Subject.Contains(certSubject)) 
     { 
      // We found it. 

      // Get its associated CSP and private key 
      csp = (RSACryptoServiceProvider)cert.PrivateKey; 
     } 

    } 

    if (csp == null) 
    { 
     throw new Exception("No valid cert was found"); 
    } 

    // Hash the data 

    SHA1Managed sha1 = new SHA1Managed(); 

    UnicodeEncoding encoding = new UnicodeEncoding(); 

    byte[] data = encoding.GetBytes(text); 

    byte[] hash = sha1.ComputeHash(data); 

    // Sign the hash 

    return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); 

} 

    static bool Verify(string text, byte[] signature, X509Certificate2 cert) 
    { 

     // Load the certificate we’ll use to verify the signature from a file 

     // X509Certificate2 cert = new X509Certificate2(certPath); 

     // Note: 

     // If we want to use the client cert in an ASP.NET app, we may use something like this instead: 

     // X509Certificate2 cert = new X509Certificate2(Request.ClientCertificate.Certificate); 

     // Get its associated CSP and public key 

     RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key; 

     // Hash the data 

     SHA1Managed sha1 = new SHA1Managed(); 

     UnicodeEncoding encoding = new UnicodeEncoding(); 

     byte[] data = encoding.GetBytes(text); 

     byte[] hash = sha1.ComputeHash(data); 

     // Verify the signature with the hash 

     return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature); 
} 
+0

아직 읽지 못했지만 코드를 읽기가 어려웠 기 때문에 서식을 변경했습니다. –

+1

@PrafullHowal Chris 구현이 사용하는 코드의 10 배 이상을 사용하여 * "다른 구현"*을 제시했습니다. 이것은 정확히 이점이 아닙니다. 구현의 어떤 장점을 전혀 고려해야합니까? – mkl

관련 문제