public void Rng() { RSAPKCS1KeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); Assert.IsNull(keyex.Rng, "Rng 1"); keyex.Rng = RandomNumberGenerator.Create(); Assert.IsNotNull(keyex.Rng, "Rng 2"); }
public static void VerifyDecryptKeyExchangePkcs1() { using (RSA rsa = RSAFactory.Create()) { var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); var deformatter = new RSAPKCS1KeyExchangeDeformatter(rsa); VerifyDecryptKeyExchange(formatter, deformatter); } }
public static void VerifyDecryptKeyExchangePkcs1() { using (RSA rsa = RSAFactory.Create()) { var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); var deformatter = new RSAPKCS1KeyExchangeDeformatter(rsa); VerifyDecryptKeyExchange(formatter, deformatter); } }
/// <summary> /// Bobの交換鍵から、 /// 「暗号化に使用する秘密鍵」と「Bobと交換するAliceの交換鍵」を生成 /// </summary> protected override void CreateKeys() { RSA rsa = (RSA)this._asa; this._aes = new AesCryptoServiceProvider(); // 秘密鍵 RSAPKCS1KeyExchangeFormatter keyExchangeFormatter = new RSAPKCS1KeyExchangeFormatter(rsa); this._exchangeKey = keyExchangeFormatter.CreateKeyExchange(this._aes.Key, typeof(Aes)); // 交換鍵 }
public static void RSAPKCS1FormatterRng() { using (RSA key = RSA.Create()) { RSAPKCS1KeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); Assert.Null(keyex.Rng); keyex.Rng = RandomNumberGenerator.Create(); Assert.NotNull(keyex.Rng); } }
public static void RSAPKCS1FormatterRng() { using (RSA key = RSA.Create()) { RSAPKCS1KeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); Assert.Null(keyex.Rng); keyex.Rng = RandomNumberGenerator.Create(); Assert.NotNull(keyex.Rng); } }
public void Properties() { RSAPKCS1KeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(); keyex.SetKey(key); AssertEquals("RSAPKCS1KeyExchangeFormatter.Parameters", "<enc:KeyEncryptionMethod enc:Algorithm=\"http://www.microsoft.com/xml/security/algorithm/PKCS1-v1.5-KeyEx\" xmlns:enc=\"http://www.microsoft.com/xml/security/encryption/v1.0\" />", keyex.Parameters); // null (default) AssertNull("RSAPKCS1KeyExchangeFormatter.Rng", keyex.Rng); AssertEquals("RSAPKCS1KeyExchangeFormatter.ToString()", "System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter", keyex.ToString()); }
/// <summary> /// Encrypts a file at <see cref="path"/> using the cert at <see cref="certCerPath"/> /// </summary> /// <param name="path"></param> /// <param name="certCerPath"></param> /// <returns></returns> public static void EncryptFile(string path, string certCerPath) { //test inputs TestEnDeCryptInputs(path, certCerPath, String.Empty); var encFile = Path.Combine(Path.GetDirectoryName(path) ?? Environment.CurrentDirectory, Path.GetFileName(path) + NF_CRYPTO_EXT); //import the cert var cert = new X509Certificate2(certCerPath); var pubKey = cert.PublicKey.Key; using (var aes = new AesManaged()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; using (var trns = aes.CreateEncryptor()) { var keyFm = new RSAPKCS1KeyExchangeFormatter(pubKey); var enKey = keyFm.CreateKeyExchange(aes.Key, aes.GetType()); var lenK = BitConverter.GetBytes(enKey.Length); var lIv = BitConverter.GetBytes(aes.IV.Length); using (var outFs = new FileStream(encFile, FileMode.Create)) { outFs.Write(lenK, 0, 4); outFs.Write(lIv, 0, 4); outFs.Write(enKey, 0, enKey.Length); outFs.Write(aes.IV, 0, aes.IV.Length); using (var cryptStream = new CryptoStream(outFs, trns, CryptoStreamMode.Write)) { var blockSz = aes.BlockSize / 8; var data = new byte[blockSz]; using (var inFs = new FileStream(path, FileMode.Open)) { var count = 0; do { count = inFs.Read(data, 0, blockSz); cryptStream.Write(data, 0, count); } while (count > 0); inFs.Close(); } cryptStream.FlushFinalBlock(); cryptStream.Close(); } outFs.Close(); } } } }
public void Encrypt(Stream inStream, Stream outStream, AsymmetricAlgorithm rsaPublicKey) { using (AesManaged aesManaged = new AesManaged()) { // Create instance of AesManaged for symetric encryption of the data. aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); // Create byte arrays to contain the length values of the key and IV. byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); // Write the following to the FileStream for the encrypted file (outFs): // - length of the key // - length of the IV // - ecrypted key // - the IV // - the encrypted cipher content outStream.Write(LenK, 0, 4); outStream.Write(LenIV, 0, 4); outStream.Write(keyEncrypted, 0, lKey); outStream.Write(aesManaged.IV, 0, lIV); // Now write the cipher text using a CryptoStream for encrypting. using (CryptoStream outStreamEncrypted = new CryptoStream(outStream, transform, CryptoStreamMode.Write)) { { int bytesRead = 0; int blockSizeBytes = aesManaged.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; while ((bytesRead = inStream.Read(data, 0, blockSizeBytes)) > 0) { outStreamEncrypted.Write(data, 0, bytesRead); } } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } } } }
public static void VerifyDecryptKeyExchangePkcs1() { using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(TestData.RSA2048Params); var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); var deformatter = new RSAPKCS1KeyExchangeDeformatter(rsa); VerifyDecryptKeyExchange(formatter, deformatter); } }
public byte[] Encrypt(byte[] content, RSACng rsaPublicKey) { using (var aesManaged = new AesManaged()) { aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (var transform = aesManaged.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); var keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); var LenK = new byte[4]; var LenIV = new byte[4]; var lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); var lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); using (var outFs = new MemoryStream()) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(aesManaged.IV, 0, lIV); using (var outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { // By encrypting a chunk at // a time, you can save memory // and accommodate large files. var count = 0; var offset = 0; // blockSizeBytes can be any arbitrary size. var blockSizeBytes = aesManaged.BlockSize / 8; var data = new byte[blockSizeBytes]; var bytesRead = 0; using (var inFs = new MemoryStream(content)) { do { count = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += blockSizeBytes; }while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); return(outFs.ToArray()); } } } }
//https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.publickey?view=net-5.0 public string EncryptToBase64(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text); byte[] encryptedBytes; using (Aes aes = Aes.Create()) { // Create instance of Aes for // symetric encryption of the data. aes.KeySize = 256; aes.Mode = CipherMode.CBC; using (ICryptoTransform transform = aes.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(_rsa); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aes.Key, aes.GetType()); // Create byte arrays to contain // the length values of the key and IV. byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aes.IV.Length; LenIV = BitConverter.GetBytes(lIV); // Write the following to the MemoryStream // for the encrypted file (outStream): // - length of the key // - length of the IV // - ecrypted key // - the IV // - the encrypted cipher content using (MemoryStream outStream = new MemoryStream()) { outStream.Write(LenK, 0, 4); outStream.Write(LenIV, 0, 4); outStream.Write(keyEncrypted, 0, lKey); outStream.Write(aes.IV, 0, lIV); // Now write the cipher text using // a CryptoStream for encrypting. using (CryptoStream outStreamEncrypted = new CryptoStream(outStream, transform, CryptoStreamMode.Write)) { outStreamEncrypted.Write(bytes, 0, bytes.Length); outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } encryptedBytes = outStream.ToArray(); } } } return(Convert.ToBase64String(encryptedBytes)); }
public void KeyExchangeMax() { AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); byte[] M = new byte [(key.KeySize >> 3) - 11]; byte[] EM = keyex.CreateKeyExchange(M); AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter(key); byte[] Mback = keyback.DecryptKeyExchange(EM); AssertEquals("RSAPKCS1KeyExchangeFormatter 1", M, Mback); }
public void KeyExchangeMin() { AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); byte[] M = { 0x01 }; byte[] EM = keyex.CreateKeyExchange(M); AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter(key); byte[] Mback = keyback.DecryptKeyExchange(EM); AssertEquals("RSAPKCS1KeyExchangeFormatter 1", M, Mback); }
public void KeyExchange128bits() { AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter(key); byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 }; byte[] EM = keyex.CreateKeyExchange(M, typeof(Rijndael)); AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter(key); byte[] Mback = keyback.DecryptKeyExchange(EM); AssertEquals("RSAPKCS1KeyExchangeFormatter 1", M, Mback); }
public byte[] EncryptWithX509(byte[] bytesToEncrypt) { // TODO: Exercise 1: Task 3a: Get the public key from the X509 certificate. var provider = (RSACryptoServiceProvider)this._certificate.PublicKey.Key; // TODO: Exercise 1: Task 3b: Create an instance of the AesManaged algorithm. using (var algorithm = new AesManaged()) { // TODO: Exercise 1: Task 3c: Create an underlying stream for the unencrypted data. using (var outStream = new MemoryStream()) { // TODO: Exercise 1: Task 3d: Create an AES encryptor based on the key and IV. using (var encryptor = algorithm.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(provider); var encryptedKey = keyFormatter.CreateKeyExchange(algorithm.Key, algorithm.GetType()); // TODO: Exercise 1: Task 3e: Create byte arrays to get the length of the encryption key and IV. var keyLength = BitConverter.GetBytes(encryptedKey.Length); var ivLength = BitConverter.GetBytes(algorithm.IV.Length); // TODO: Exercise 1: Task 3f: Write the following to the out stream: // 1) the length of the encryption key. // 2) the length of the IV. // 3) the encryption key. // 4) the IV. outStream.Write(keyLength, 0, keyLength.Length); outStream.Write(ivLength, 0, ivLength.Length); outStream.Write(encryptedKey, 0, encryptedKey.Length); outStream.Write(algorithm.IV, 0, algorithm.IV.Length); // TODO: Exercise 1: Task 3g: Create a CryptoStream that will write the encypted data to the underlying buffer. using (var encrypt = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write)) { // TODO: Exercise 1: Task 3h: Write all the data to the stream. encrypt.Write(bytesToEncrypt, 0, bytesToEncrypt.Length); encrypt.FlushFinalBlock(); // TODO: Exercise 1: Task 3i: Return the encrypted buffered data as a byte[]. return(outStream.ToArray()); } } } } }
public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool fOAEP) { AsymmetricKeyExchangeFormatter formatter = null; if (fOAEP) { formatter = new RSAOAEPKeyExchangeFormatter(rsa); } else { formatter = new RSAPKCS1KeyExchangeFormatter(rsa); } return(formatter.CreateKeyExchange(keyData)); }
public static Boolean Test() { Boolean bRes = true; RSAPKCS1KeyExchangeFormatter pcef1 = new RSAPKCS1KeyExchangeFormatter(RSA.Create()); RSAPKCS1KeyExchangeDeformatter pced1 = new RSAPKCS1KeyExchangeDeformatter(RSA.Create()); Console.WriteLine("pcef1 parameters: " + pcef1.Parameters + "\npced1 parameters: " + pced1.Parameters); bRes = TestKeyExchange(pcef1, pced1, false) && bRes; RSA rsa = RSA.Create(); RandomNumberGenerator rng = new RNGCryptoServiceProvider(); RSAPKCS1KeyExchangeFormatter pcef2 = new RSAPKCS1KeyExchangeFormatter(); RSAPKCS1KeyExchangeDeformatter pced2 = new RSAPKCS1KeyExchangeDeformatter(rsa); RSA rsa1 = RSA.Create(); rsa1.ImportParameters(rsa.ExportParameters(false)); pcef2.SetKey(rsa1); pcef2.Rng = rng; pced2.RNG = rng; Console.WriteLine("pcef2 parameters: " + pcef2.Parameters + "\npced2 parameters: " + pced2.Parameters); bRes = TestKeyExchange(pcef2, pced2, true) && bRes; RSAOAEPKeyExchangeFormatter ocef1 = new RSAOAEPKeyExchangeFormatter(RSA.Create()); RSAOAEPKeyExchangeDeformatter oced1 = new RSAOAEPKeyExchangeDeformatter(RSA.Create()); Console.WriteLine("ocef1 parameters: " + ocef1.Parameters + "\noced1 parameters: " + oced1.Parameters); bRes = TestKeyExchange(ocef1, oced1, false) && bRes; rsa = RSA.Create(); rng = new RNGCryptoServiceProvider(); RSAOAEPKeyExchangeFormatter ocef2 = new RSAOAEPKeyExchangeFormatter(); RSAOAEPKeyExchangeDeformatter oced2 = new RSAOAEPKeyExchangeDeformatter(rsa); rsa1 = RSA.Create(); rsa1.ImportParameters(rsa.ExportParameters(false)); ocef2.SetKey(rsa1); ocef2.Rng = rng; // oced2.RNG = rng; Console.WriteLine("ocef2 parameters: " + ocef2.Parameters + "\noced2 parameters: " + oced2.Parameters); bRes = TestKeyExchange(ocef2, oced2, true) && bRes; return(bRes); }
public byte[] Encrypt(byte[] rgb, bool fOAEP) { // choose between OAEP or PKCS#1 v.1.5 padding AsymmetricKeyExchangeFormatter fmt = null; if (fOAEP) { fmt = new RSAOAEPKeyExchangeFormatter(rsa); } else { fmt = new RSAPKCS1KeyExchangeFormatter(rsa); } return(fmt.CreateKeyExchange(rgb)); }
byte[] EncryptWithX509(byte[] bytesToEncypt) { // Get the public key from the X509 certificate. This key will be used to encrypt the AesManaged encryption key. var provider = (RSACryptoServiceProvider)this._certificate.PrivateKey; // Create an instance of the AesManaged algorithm which we will use to encrypt the data with. using (var algorithm = new AesManaged()) { // Create an underlying stream which the decrypted data will be buffered too. using (var outStream = new MemoryStream()) { // Create an AES encryptor based on the key and IV. using (var encryptor = algorithm.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(provider); var encryptedKey = keyFormatter.CreateKeyExchange(algorithm.Key, algorithm.GetType()); // Create byte arrays to get the length of the encryption key and IV. var keyLength = BitConverter.GetBytes(encryptedKey.Length); var ivLength = BitConverter.GetBytes(algorithm.IV.Length); // Write the following to the out stream: // 1) the length of the encryption key. // 2) the length of the IV. // 3) the encryption key. // 4) the IV. // 5) the encrypted data. outStream.Write(keyLength, 0, 4); outStream.Write(ivLength, 0, 4); outStream.Write(encryptedKey, 0, encryptedKey.Length); outStream.Write(algorithm.IV, 0, algorithm.IV.Length); // Create a CryptoStream that will write the encypted data to the underlying buffer. using (var encrypt = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write)) { // Write all the data to the stream. encrypt.Write(bytesToEncypt, 0, bytesToEncypt.Length); encrypt.FlushFinalBlock(); // Return the encrypted buffered data as a byte[]. return(outStream.ToArray()); } } } } }
private static void EncryptData(Stream output, Stream input, AsymmetricAlgorithm rsaPublicKey) { using (AesManaged aesManaged = new AesManaged()) { aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); output.Write(LenK, 0, 4); output.Write(LenIV, 0, 4); output.Write(keyEncrypted, 0, lKey); output.Write(aesManaged.IV, 0, lIV); using (CryptoStream streamEncrypted = new CryptoStream(output, transform, CryptoStreamMode.Write)) { int count = 0; int offset = 0; int blockSizeBytes = aesManaged.BlockSize / 8; byte[] buffer = new byte[blockSizeBytes]; int bytesRead = 0; do { count = input.Read(buffer, 0, blockSizeBytes); offset += count; streamEncrypted.Write(buffer, 0, count); bytesRead += blockSizeBytes; }while (count > 0); input.Close(); streamEncrypted.FlushFinalBlock(); streamEncrypted.Close(); } } } }
/// <summary> /// Detects if RSACng is available /// </summary> /// <returns></returns> internal static bool IsRsaCngSupported() { Type rsaCng = GetSystemCoreType(RSACngTypeName, throwOnError: false); // If the type doesn't exist, there can't be good support for it. // (System.Core < 4.6) if (rsaCng == null) { return(false); } Type dsaCng = GetSystemCoreType(DSACngTypeName, throwOnError: false); // The original implementation of RSACng returned shared objects in the CAPI fallback // pathway. That behavior is hard to test for, since CNG can load all CAPI software keys. // But, since DSACng was added in 4.6.2, and RSACng better guarantees uniqueness in 4.6.2 // use that coincidence as a compatibility test. // // If DSACng is missing, RSACng usage might lead to attempting to use Disposed objects // (System.Core < 4.6.2) if (dsaCng == null) { return(false); } // Create an RSACng instance and send it to RSAPKCS1KeyExchangeFormatter. It was adjusted to // be CNG-capable for 4.6.2; and other types in that library also are up-to-date. // // If mscorlib can't handle it properly, then other libraries probably can't, so we'll keep // preferring RSACryptoServiceProvider. RSA rsa = (RSA)Activator.CreateInstance(rsaCng); try { RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter(rsa); formatter.CreateKeyExchange(new byte[1]); } catch (Exception) { // (mscorlib < 4.6.2) return(false); } return(true); }
/// <inheritdoc /> protected internal override byte[] Encrypt(byte[] data, byte[] iv) { #if NETCOREAPP1_0 switch (this.algorithm) { case AsymmetricAlgorithm.RsaPkcs1: return(this.Rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1)); case AsymmetricAlgorithm.RsaOaepSha1: return(this.Rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1)); case AsymmetricAlgorithm.RsaOaepSha256: return(this.Rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256)); case AsymmetricAlgorithm.RsaOaepSha384: return(this.Rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA384)); case AsymmetricAlgorithm.RsaOaepSha512: return(this.Rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA512)); default: throw new PlatformNotSupportedException(); } #else AsymmetricKeyExchangeFormatter keyExchange; switch (this.Algorithm) { case AsymmetricAlgorithm.RsaOaepSha1: case AsymmetricAlgorithm.RsaOaepSha256: case AsymmetricAlgorithm.RsaOaepSha384: case AsymmetricAlgorithm.RsaOaepSha512: keyExchange = new RSAOAEPKeyExchangeFormatter(this.Rsa); break; case AsymmetricAlgorithm.RsaPkcs1: keyExchange = new RSAPKCS1KeyExchangeFormatter(this.Rsa); break; default: throw new NotSupportedException(); } return(keyExchange.CreateKeyExchange(data)); #endif }
/// <summary> /// Performs a simple encryption of inputData using a /// combination of PublicKey + SymmetricKey encryption. /// </summary> /// <param name="rsa">The RSA.</param> /// <param name="input">The input.</param> /// <returns></returns> /// <remarks>See: http://pages.infinit.net/ctech/20031101-0151.html </remarks> public static byte[] SimpleEncrypt(RSA rsa, byte[] input) { var sa = SymmetricAlgorithm.Create("AES"); var ct = sa.CreateEncryptor(); byte[] encrypt = ct.TransformFinalBlock(input, 0, input.Length); var fmt = new RSAPKCS1KeyExchangeFormatter(rsa); byte[] keyex = fmt.CreateKeyExchange(sa.Key); // return the key exchange, the IV (public) and encrypted data byte[] result = new byte[keyex.Length + sa.IV.Length + encrypt.Length]; Buffer.BlockCopy(keyex, 0, result, 0, keyex.Length); Buffer.BlockCopy(sa.IV, 0, result, keyex.Length, sa.IV.Length); Buffer.BlockCopy(encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length); return(result); }
public static Boolean Test() { Boolean bRes = true; RSAPKCS1KeyExchangeFormatter pcef1 = new RSAPKCS1KeyExchangeFormatter(RSA.Create()); RSAPKCS1KeyExchangeDeformatter pced1 = new RSAPKCS1KeyExchangeDeformatter(RSA.Create()); Console.WriteLine("pcef1 parameters: " + pcef1.Parameters + "\npced1 parameters: " + pced1.Parameters); bRes = TestKeyExchange(pcef1, pced1, false) && bRes; RSA rsa = RSA.Create(); RandomNumberGenerator rng = new RNGCryptoServiceProvider(); RSAPKCS1KeyExchangeFormatter pcef2 = new RSAPKCS1KeyExchangeFormatter(); RSAPKCS1KeyExchangeDeformatter pced2 = new RSAPKCS1KeyExchangeDeformatter(rsa); RSA rsa1 = RSA.Create(); rsa1.ImportParameters(rsa.ExportParameters(false)); pcef2.SetKey(rsa1); pcef2.Rng = rng; pced2.RNG = rng; Console.WriteLine("pcef2 parameters: " + pcef2.Parameters + "\npced2 parameters: " + pced2.Parameters); bRes = TestKeyExchange(pcef2, pced2, true) && bRes; RSAOAEPKeyExchangeFormatter ocef1 = new RSAOAEPKeyExchangeFormatter(RSA.Create()); RSAOAEPKeyExchangeDeformatter oced1 = new RSAOAEPKeyExchangeDeformatter(RSA.Create()); Console.WriteLine("ocef1 parameters: " + ocef1.Parameters + "\noced1 parameters: " + oced1.Parameters); bRes = TestKeyExchange(ocef1, oced1, false) && bRes; rsa = RSA.Create(); rng = new RNGCryptoServiceProvider(); RSAOAEPKeyExchangeFormatter ocef2 = new RSAOAEPKeyExchangeFormatter(); RSAOAEPKeyExchangeDeformatter oced2 = new RSAOAEPKeyExchangeDeformatter(rsa); rsa1 = RSA.Create(); rsa1.ImportParameters(rsa.ExportParameters(false)); ocef2.SetKey(rsa1); ocef2.Rng = rng; // oced2.RNG = rng; Console.WriteLine("ocef2 parameters: " + ocef2.Parameters + "\noced2 parameters: " + oced2.Parameters); bRes = TestKeyExchange(ocef2, oced2, true) && bRes; return bRes; }
//............................................................................... #region Encrypt/Decrypt the Key (Asymmetric) and the Data (Symmetric) //............................................................................... static void EncryptStream(Stream inputStream, Stream outputStream, AsymmetricAlgorithm keyEncryption, SymmetricAlgorithm dataEncryption) { if (null == inputStream) { throw new ArgumentNullException(nameof(inputStream)); } if (null == outputStream) { throw new ArgumentNullException(nameof(outputStream)); } if (null == keyEncryption) { throw new ArgumentNullException(nameof(keyEncryption)); } if (null == dataEncryption) { throw new ArgumentNullException(nameof(dataEncryption)); } // About... // Trace.WriteLine($"Encrypting. KEK: {keyEncryption.GetType().Name} / {keyEncryption.KeySize} bits"); // Trace.WriteLine($"Encrypting. DEK: {dataEncryption.GetType().Name} / {dataEncryption.KeySize} bits / BlockSize: {dataEncryption.BlockSize} bits"); // The DataEncryptionKey and the IV. var DEK = dataEncryption.Key ?? throw new Exception("SymmetricAlgorithm.Key was NULL"); var IV = dataEncryption.IV ?? throw new Exception("SymmetricAlgorithm.IV was NULL"); // Encrypt the DataEncryptionKey and the IV var keyFormatter = new RSAPKCS1KeyExchangeFormatter(keyEncryption); var encryptedDEK = keyFormatter.CreateKeyExchange(DEK); var encryptedIV = keyFormatter.CreateKeyExchange(IV); // Write the Encrypted DEK and IV outputStream.WriteLengthAndBytes(encryptedDEK); outputStream.WriteLengthAndBytes(encryptedIV); // Write the encrypted data. // Note: Disposing the CryptoStream also disposes the outputStream. There is no keepOpen option. using (var transform = dataEncryption.CreateEncryptor()) using (var cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write)) { inputStream.CopyTo(cryptoStream, bufferSize: dataEncryption.BlockSize * 4); } }
public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) { if (keyData == null) { throw new ArgumentNullException("keyData"); } if (rsa == null) { throw new ArgumentNullException("rsa"); } if (useOAEP) { RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter(rsa); return(formatter.CreateKeyExchange(keyData)); } RSAPKCS1KeyExchangeFormatter formatter2 = new RSAPKCS1KeyExchangeFormatter(rsa); return(formatter2.CreateKeyExchange(keyData)); }
// Use the RSAPKCS1KeyExchangeDeformatter class to decode the // specified message. public byte[] EncodeMessage(string message) { byte[] encodedMessage = null; try { // Construct a formatter with the specified RSA key. RSAPKCS1KeyExchangeFormatter keyEncryptor = new RSAPKCS1KeyExchangeFormatter(rsaKey); // Convert the message to bytes to create the encrypted data. byte[] byteMessage = Encoding.ASCII.GetBytes(message); encodedMessage = keyEncryptor.CreateKeyExchange(byteMessage); } catch (Exception ex) { Console.WriteLine("Unexpected exception caught:" + ex.ToString()); } return(encodedMessage); }
public void ProcessCommon(bool sendLength) { // Compute pre master secret var preMasterSecret = Context.Negotiating.Cipher.CreatePremasterSecret(); // Create a new RSA key RSA rsa = null; if (Context.ServerSettings.ServerKeyExchange) { // this is the case for "exportable" ciphers rsa = new RSAManaged(); rsa.ImportParameters(Context.ServerSettings.RsaParameters); } else { rsa = Context.ServerSettings.CertificateRSA; } // Encrypt premaster_sercret var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); // Write the preMasterSecret encrypted var buffer = formatter.CreateKeyExchange(preMasterSecret); if (sendLength) { Write((short)buffer.Length); } Write(buffer); // Create master secret Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret); // Create keys Context.Negotiating.Cipher.ComputeKeys(); // Clear resources rsa.Clear(); }
private byte[] Encrypt(RSA rsa, byte[] input) { // by default this will create a 128 bits AES (Rijndael) object byte[] result; using (var sa = SymmetricAlgorithm.Create()) { using (var ct = sa.CreateEncryptor()) { var encrypt = ct.TransformFinalBlock(input, 0, input.Length); var fmt = new RSAPKCS1KeyExchangeFormatter(rsa); var keyex = fmt.CreateKeyExchange(sa.Key); // return the key exchange, the IV (public) and encrypted data result = new byte[keyex.Length + sa.IV.Length + encrypt.Length]; Buffer.BlockCopy(keyex, 0, result, 0, keyex.Length); Buffer.BlockCopy(sa.IV, 0, result, keyex.Length, sa.IV.Length); Buffer.BlockCopy(encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length); } } return(result); }
//<Snippet2> private static void Send(RSA key, string secretMessage, out byte[] iv, out byte[] encryptedSessionKey, out byte[] encryptedMessage) { using (Aes aes = new AesCryptoServiceProvider()) { iv = aes.IV; // Encrypt the session key RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(key); encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes)); // Encrypt the message using (MemoryStream ciphertext = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] plaintextMessage = Encoding.UTF8.GetBytes(secretMessage); cs.Write(plaintextMessage, 0, plaintextMessage.Length); cs.Close(); encryptedMessage = ciphertext.ToArray(); } } }
static void Main(string[] args) { Console.WriteLine("This example shows how to use the public and private key from a certificate to encrypt and decrypt data.\r\n"); byte[] data = Encoding.ASCII.GetBytes("Hello World!"); // load the certificate from a file Certificate cert = Certificate.CreateFromCerFile(@"client.cer"); // get an RSA instance that represents the public key of the certificate RSA public_key = cert.PublicKey; // create a PKCS#1 key exchange formatter instance with the public key RSAPKCS1KeyExchangeFormatter kef = new RSAPKCS1KeyExchangeFormatter(public_key); // encrypt the data, using the public key from the certificate byte[] encrypted = kef.CreateKeyExchange(data); // associate the certificate with its private key // we set exportable to true because decryption will fail on Windows 98 // if this flag is not set. If you do not use Windows 98, you should set // the exportable flag to false for increased security. cert.AssociateWithPrivateKey(@"client.pvk", "test", true); // get an RSA instance that represents the private key RSA private_key = cert.PrivateKey; // create a PKCS#1 key exchange deformatter instance with the private key RSAPKCS1KeyExchangeDeformatter ked = new RSAPKCS1KeyExchangeDeformatter(private_key); // decrypt the data, using the private key from the certificate byte[] decrypted = ked.DecryptKeyExchange(encrypted); // print the results in the console Console.WriteLine("Input data: " + Encoding.ASCII.GetString(data) + "\r\n"); Console.WriteLine("Encrypted data:\r\n" + BytesToHex(encrypted) + "\r\n"); Console.WriteLine("Decrypted data: " + Encoding.ASCII.GetString(decrypted)); Console.WriteLine("\r\nPress ENTER to continue..."); Console.ReadLine(); // clean up public_key.Clear(); private_key.Clear(); }
public static string Encrypt(string text) { var input = Encoding.UTF8.GetBytes(text); // by default this will create a 128 bits AES (Rijndael) object SymmetricAlgorithm sa = SymmetricAlgorithm.Create(); ICryptoTransform ct = sa.CreateEncryptor(); byte[] encrypt = ct.TransformFinalBlock(input, 0, input.Length); using (var rsa = GetDefaultRsaKey()) { var fmt = new RSAPKCS1KeyExchangeFormatter(rsa); byte[] keyex = fmt.CreateKeyExchange(sa.Key); // return the key exchange, the IV (public) and encrypted data byte[] result = new byte [keyex.Length + sa.IV.Length + encrypt.Length]; Buffer.BlockCopy(keyex, 0, result, 0, keyex.Length); Buffer.BlockCopy(sa.IV, 0, result, keyex.Length, sa.IV.Length); Buffer.BlockCopy(encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length); return(Convert.ToBase64String(result)); } }
static void Main(string[] args) { Console.WriteLine("This example shows how to use the public and private key from a certificate to encrypt and decrypt data.\r\n"); byte[] data = Encoding.ASCII.GetBytes("Hello World!"); // load the certificate from a file Certificate cert = Certificate.CreateFromCerFile(@"client.cer"); // get an RSA instance that represents the public key of the certificate RSA public_key = cert.PublicKey; // create a PKCS#1 key exchange formatter instance with the public key RSAPKCS1KeyExchangeFormatter kef = new RSAPKCS1KeyExchangeFormatter(public_key); // encrypt the data, using the public key from the certificate byte[] encrypted = kef.CreateKeyExchange(data); // associate the certificate with its private key // we set exportable to true because decryption will fail on Windows 98 // if this flag is not set. If you do not use Windows 98, you should set // the exportable flag to false for increased security. cert.AssociateWithPrivateKey(@"client.pvk", "test", true); // get an RSA instance that represents the private key RSA private_key = cert.PrivateKey; // create a PKCS#1 key exchange deformatter instance with the private key RSAPKCS1KeyExchangeDeformatter ked = new RSAPKCS1KeyExchangeDeformatter(private_key); // decrypt the data, using the private key from the certificate byte[] decrypted = ked.DecryptKeyExchange(encrypted); // print the results in the console Console.WriteLine("Input data: " + Encoding.ASCII.GetString(data) + "\r\n"); Console.WriteLine("Encrypted data:\r\n" + BytesToHex(encrypted) + "\r\n"); Console.WriteLine("Decrypted data: " + Encoding.ASCII.GetString(decrypted)); Console.WriteLine("\r\nPress ENTER to continue..."); Console.ReadLine(); // clean up public_key.Clear(); private_key.Clear(); }
/********************* * Encryption methods * Lifted from: * http://www.go-mono.com/docs/index.aspx?link=M%3aSystem.Security.Cryptography.RSACryptoServiceProvider.Encrypt(System.Byte%5b%5d%2cSystem.Boolean) * http://www.go-mono.com/docs/index.aspx?link=M%3aSystem.Security.Cryptography.RSACryptoServiceProvider.Decrypt(System.Byte%5b%5d%2cSystem.Boolean) * respectively *********************/ private byte[] Encrypt(RSA rsa, byte[] input) { // by default this will create a 128 bits AES (Rijndael) object SymmetricAlgorithm sa = SymmetricAlgorithm.Create (); ICryptoTransform ct = sa.CreateEncryptor (); byte[] encrypt = ct.TransformFinalBlock (input, 0, input.Length); RSAPKCS1KeyExchangeFormatter fmt = new RSAPKCS1KeyExchangeFormatter (rsa); byte[] keyex = fmt.CreateKeyExchange (sa.Key); // return the key exchange, the IV (public) and encrypted data byte[] result = new byte [keyex.Length + sa.IV.Length + encrypt.Length]; Buffer.BlockCopy (keyex, 0, result, 0, keyex.Length); Buffer.BlockCopy (sa.IV, 0, result, keyex.Length, sa.IV.Length); Buffer.BlockCopy (encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length); return result; }