2013-04-26 6 views
0

PGP 암호화 CSV 파일을 SFTP로 보낼 수있는 요구 사항이 있습니다. 많은 연구 끝에 인터넷에서 'Bouncy Castle' Library'코드를 사용하고 있습니다. 코드는 gogod로 보이지만 PGP에서 저의 경험이 없다면 저에게 효과적이지 않습니다. 에 적합한 값을 찾는 제발 도와주세요 : 당신은받는 사람의 공개 키를 얻어야한다Bouncy Castle Encryption

namespace PgpEncryption 
{ 
    class Program 
    { 
     public static void Main() 
     { 
      EncryptAndSign(); 
     } 

     private static void EncryptAndSign() 
     { 
      string publicKeyFileName = ""; 
      string privateKeyFileName = ""; 
      string pasPhrase = "";  
      PgpEncryptionKeys encryptionKeys 
       = new PgpEncryptionKeys(publicKeyFileName, privateKeyFileName, pasPhrase); 
      PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys); 
      string encryptedFileName = ""; 
      using (Stream outputStream = File.Create(encryptedFileName)) 
      { 
       string fileToEncrypt = "";  
       encrypter.EncryptAndSign(outputStream, new FileInfo(fileToEncrypt)); 
      }  
     } 
    } 
} 

public class PgpEncryptionKeys 
{ 
    public PgpEncryptionKeys(string publicKeyPath, string privateKeyPath, string passPhrase) 
    { 
     if (!File.Exists(publicKeyPath)) 
      throw new ArgumentException("Public key file not found", "publicKeyPath"); 
     if (!File.Exists(privateKeyPath)) 
      throw new ArgumentException("Private key file not found", "privateKeyPath"); 
     if (String.IsNullOrEmpty(passPhrase)) 
      throw new ArgumentException("passPhrase is null or empty.", "passPhrase"); 
     PublicKey = ReadPublicKey(publicKeyPath); 
     SecretKey = ReadSecretKey(privateKeyPath); 
     PrivateKey = ReadPrivateKey(passPhrase); 
    } 

    #region Secret Key 
    private PgpSecretKey ReadSecretKey(string privateKeyPath) 
    { 
     using (Stream keyIn = File.OpenRead(privateKeyPath)) 
     using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) 
     { 
      PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(inputStream); 
      PgpSecretKey foundKey = GetFirstSecretKey(secretKeyRingBundle); 
      if (foundKey != null) 
       return foundKey;    
     } 
     throw new ArgumentException("Can't find signing key in key ring."); 
    } 

    private PgpSecretKey GetFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle) 
    { 
     foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings()) 
     { 
      PgpSecretKey key = (PgpSecretKey)kRing.GetSecretKeys(); 
      if (key != null) 
       return key; 
     } 
     return null; 
    } 
    #endregion 

    #region Public Key 
    private PgpPublicKey ReadPublicKey(string publicKeyPath) 
    { 
     using (Stream keyIn = File.OpenRead(publicKeyPath)) 
     using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) 
     { 
      PgpPublicKeyRingBundle publicKeyRingBundle = new PgpPublicKeyRingBundle(inputStream); 
      PgpPublicKey foundKey = GetFirstPublicKey(publicKeyRingBundle); 
      if (foundKey != null) 
       return foundKey; 
     } 
     throw new ArgumentException("No encryption key found in public key ring."); 
    } 

    private PgpPublicKey GetFirstPublicKey(PgpPublicKeyRingBundle publicKeyRingBundle) 
    { 
     foreach (PgpPublicKeyRing kRing in publicKeyRingBundle.GetKeyRings()) 
     { 
      PgpPublicKey key = (PgpPublicKey)kRing.GetPublicKeys(); 
      //PgpPublicKey key = kRing.GetPublicKeys() 
           //.Cast<PgpPublicKey>() 
           // .Where(k => k.IsEncryptionKey) 
           // .FirstOrDefault(); 
      if (key != null) 
       return key; 
     } 
     return null; 
    } 
    #endregion 

    #region Private Key 
    private PgpPrivateKey ReadPrivateKey(string passPhrase) 
    { 
     PgpPrivateKey privateKey = SecretKey.ExtractPrivateKey(passPhrase.ToCharArray()); 
     if (privateKey != null) 
      return privateKey; 
     throw new ArgumentException("No private key found in secret key."); 
    } 
    #endregion   
} 


public class PgpEncrypt 
{ 

    private PgpEncryptionKeys m_encryptionKeys; 
    private const int BufferSize = 0x10000; // should always be power of 2 

    /// <summary> 
    /// Instantiate a new PgpEncrypt class with initialized PgpEncryptionKeys. 
    /// </summary> 
    /// <param name="encryptionKeys"></param> 
    /// <exception cref="ArgumentNullException">encryptionKeys is null</exception> 
    public PgpEncrypt(PgpEncryptionKeys encryptionKeys) 
    { 

     if (encryptionKeys == null) 

      throw new ArgumentNullException("encryptionKeys", "encryptionKeys is null."); 
     m_encryptionKeys = encryptionKeys; 
    } 

    /// <summary> 
    /// Encrypt and sign the file pointed to by unencryptedFileInfo and 
    /// write the encrypted content to outputStream. 
    /// </summary> 
    /// <param name="outputStream">The stream that will contain the 
    /// encrypted data when this method returns.</param> 
    /// <param name="fileName">FileInfo of the file to encrypt</param> 
    public void EncryptAndSign(Stream outputStream, FileInfo unencryptedFileInfo) 
    { 
     if (outputStream == null) 
      throw new ArgumentNullException("outputStream", "outputStream is null."); 
     if (unencryptedFileInfo == null) 
      throw new ArgumentNullException("unencryptedFileInfo", "unencryptedFileInfo is null."); 
     if (!File.Exists(unencryptedFileInfo.FullName)) 
      throw new ArgumentException("File to encrypt not found."); 
     using (Stream encryptedOut = ChainEncryptedOut(outputStream)) 
     using (Stream compressedOut = ChainCompressedOut(encryptedOut)) 
     { 
      PgpSignatureGenerator signatureGenerator = InitSignatureGenerator compressedOut); 
      using (Stream literalOut = ChainLiteralOut(compressedOut, unencryptedFileInfo)) 
      using (FileStream inputFile = unencryptedFileInfo.OpenRead()) 
      { 
       WriteOutputAndSign(compressedOut, literalOut, inputFile, signatureGenerator); 
      } 
     } 
    } 

    private static void WriteOutputAndSign(Stream compressedOut,Stream literalOut,FileStream inputFile,PgpSignatureGenerator signatureGenerator) 
    { 
     int length = 0; 
     byte[] buf = new byte[BufferSize]; 
     while ((length = inputFile.Read(buf, 0, buf.Length)) > 0) 
     { 
      literalOut.Write(buf, 0, length); 
      signatureGenerator.Update(buf, 0, length); 
     } 
     signatureGenerator.Generate().Encode(compressedOut); 
    } 

    private Stream ChainEncryptedOut(Stream outputStream) 
    { 
     PgpEncryptedDataGenerator encryptedDataGenerator; 
     encryptedDataGenerator = 
      new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, 
              new SecureRandom()); 
     encryptedDataGenerator.AddMethod(m_encryptionKeys.PublicKey); 
     return encryptedDataGenerator.Open(outputStream, new byte[BufferSize]); 
    } 

    private static Stream ChainCompressedOut(Stream encryptedOut) 
    { 
     PgpCompressedDataGenerator compressedDataGenerator = 
      new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); 
     return compressedDataGenerator.Open(encryptedOut); 
    } 

    private static Stream ChainLiteralOut(Stream compressedOut, FileInfo file) 
    { 
     PgpLiteralDataGenerator pgpLiteralDataGenerator = new PgpLiteralDataGenerator(); 
     return pgpLiteralDataGenerator.Open(compressedOut, PgpLiteralData.Binary, file); 
    } 

    private PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut) 
    { 
     const bool IsCritical = false; 
     const bool IsNested = false; 
     PublicKeyAlgorithmTag tag = m_encryptionKeys.SecretKey.PublicKey.Algorithm; 
     PgpSignatureGenerator pgpSignatureGenerator = 
      new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1); 
     pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, m_encryptionKeys.PrivateKey); 

     foreach (string userId in m_encryptionKeys.SecretKey.PublicKey.GetUserIds()) 
     { 
      PgpSignatureSubpacketGenerator subPacketGenerator = 
       new PgpSignatureSubpacketGenerator(); 
      subPacketGenerator.SetSignerUserId(IsCritical, userId); 
      pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate()); 
      // Just the first one! 
      break; 
     } 

     pgpSignatureGenerator.GenerateOnePassVersion(IsNested).Encode(compressedOut); 
     return pgpSignatureGenerator; 
    } 
} 
+0

IIRC PGP 도구를 사용하여 직접 작성해야합니다. 거기서 자신의 암호문을 만들어서 두 파일을 모두 가져와야합니다. –

+0

키를 찾았지만 키를 사용하는 방법을 모르고 publicKeyFileName, privateKeyFileName 값은 – 14578446

답변

0

:

  • privateKeyFileName
  • 에게

    1. publicKeyFileName pasPhrase을
    2. 아래

    내 코드입니다 자신의 비밀 키를 생성하십시오 (파일에 서명해야하는 경우). 또한 PGP는 사용자의 요구에 맞는 암호 기반 암호화를 허용합니다. 또한 SecureBlackbox와 같은 상업용 라이브러리를 살펴볼 것을 권장합니다. 그들은 비용이 많이 들지만 훨씬 더 나은 지원, 데모, 문서 등을 포함합니다.

  • +0

    입니다. 일부 웹 생성기에서 키를 얻었습니다. 하지만이 코드에서 yhem을 어떻게 사용합니까? – 14578446

    +0

    파일에 저장하고 publicKeyFileName을 해당 파일을 가리 키도록 설정하십시오. –

    +0

    txt 파일에 있습니까? 나는 그것을했지만 저를 위해 일하지 않습니다. – 14578446

    0

    나는 코드 중 일부가 그리울 것 같습니까?

    public class PgpEncryptionKeys { 
        public PgpPublicKey PublicKey { get; private set; } 
        public PgpPrivateKey PrivateKey { get; private set; } 
        public PgpSecretKey SecretKey { get; private set; } 
    
    관련 문제