예제 #1
0
        public byte[] EncryptWithFileKey(string filePath, byte[] toEncrypt, string hashAlgorithm = PaddingHashAlgorithmNames.SHA512, int paddingFlags = PaddingFlags.OAEPPadding)
        {
            byte[] encryptedData = null;

            if (!File.Exists(filePath))
            {
                throw new IOException(string.Format("They file {0} does not exist and cannot be used for encryption", filePath));
            }

            byte[] keyBlob = null;

            CngKey key;

            try
            {
                key = PemHelper.ImportFromPem(filePath);
            }
            catch //Not a PEM, just import the RSA blob
            {
                keyBlob = File.ReadAllBytes(filePath);
                key     = CngKey.Import(keyBlob, new CngKeyBlobFormat("RSAPUBLICBLOB"));
            }
            using (key)
            {
                using (RSACng rsa = new RSACng(key))
                {
                    RSAEncryptionPadding padding = this.GetRSAPadding(hashAlgorithm, paddingFlags);
                    encryptedData = rsa.Encrypt(toEncrypt, padding);
                }
            }
            return(encryptedData);
        }
예제 #2
0
        /// <summary>
        /// Export the public key so that encryption can happen off of the machine.
        /// </summary>
        /// <param name="providerName">Name of the provider</param>
        /// <param name="keyName">Name of the key to destroy</param>
        /// <param name="filePath">Output Path for where to write the key</param>
        public void ExportPublicKeytoFile(string providerName, string keyName, string filePath, FileFormat fileFormat = FileFormat.CngBlob)
        {
            CngProvider provider = new CngProvider(providerName);

            bool keyExists = doesKeyExists(provider, keyName);

            if (!keyExists)
            {
                throw new CryptographicException(string.Format("They key {0} does not exist so there is no public key to export", keyName));
            }
            if (File.Exists(filePath))
            {
                throw new IOException(string.Format("File {0} already exists.", filePath));
            }
            using (CngKey key = CngKey.Open(keyName, provider, CngKeyOpenOptions.MachineKey))
            {
                if (fileFormat == FileFormat.CngBlob)
                {
                    File.WriteAllBytes(filePath, key.Export(new CngKeyBlobFormat("RSAPUBLICBLOB")));
                }
                else
                {
                    // FileFormat.PEM
                    File.WriteAllText(filePath, PemHelper.ExportToPem(key));
                }
            }
        }