Getting X509 Certificates in and Out of The Key Store
Getting X509 Certificates in and Out of The Key Store
Key Store
1. public static X509Certificate2 GetCert(string thumbprint,
2. StoreName storeName,
3. StoreLocation storeLocation)
4. {
5. // The following code gets the cert from the keystore
6. X509Store store = new X509Store(storeName, storeLocation);
7. store.Open(OpenFlags.ReadOnly);
8. X509Certificate2Collection certCollection =
9. store.Certificates.Find(X509FindType.FindByThumbprint,
10. thumbprint,
11. false);
12. X509Certificate2Enumerator enumerator =
certCollection.GetEnumerator();
13. X509Certificate2 cert = null;
14. while (enumerator.MoveNext())
15. {
16. cert = enumerator.Current;
17. }
18. return cert;
19. }
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Text;
// Encrypt the file using the public key from the certificate.
EncryptFile(originalFile,
(RSACryptoServiceProvider)cert.PublicKey.Key);
// Decrypt the file using the private key from the certificate.
DecryptFile(encryptedFile,
(RSACryptoServiceProvider)cert.PrivateKey);
outFs.Write(LenK, 0, 4);
outFs.Write(LenIV, 0, 4);
outFs.Write(keyEncrypted, 0, lKey);
outFs.Write(aesManaged.IV, 0, lIV);
// By encrypting a chunk at
// a time, you can save memory
// and accommodate large files.
int count = 0;
int offset = 0;
inFs.Seek(0, SeekOrigin.Begin);
inFs.Seek(0, SeekOrigin.Begin);
inFs.Read(LenK, 0, 3);
inFs.Seek(4, SeekOrigin.Begin);
inFs.Read(LenIV, 0, 3);
// Use RSACryptoServiceProvider
// to decrypt the AesManaged key.
byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted,
false);
int count = 0;
int offset = 0;
}
while (count > 0);
outStreamDecrypted.FlushFinalBlock();
outStreamDecrypted.Close();
}
outFs.Close();
}
inFs.Close();
}
}
}