private void AsymmetricImportExport(CryptographicKey keyPair) { String algName = AlgorithmNames.SelectionBoxItem.ToString(); AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); // Export the public key. IBuffer blobOfPublicKey = keyPair.ExportPublicKey(); IBuffer blobOfKeyPair = keyPair.Export(); SignVerifyText.Text += " Key pair was successfully exported.\n"; // Import the public key. CryptographicKey keyPublic = Algorithm.ImportPublicKey(blobOfPublicKey); // Check the key size. if (keyPublic.KeySize != keyPair.KeySize) { SignVerifyText.Text += "ImportPublicKey failed! The imported key's size did not match the original's!"; return; } SignVerifyText.Text += " Public key was successfully imported.\n"; // Import the key pair. keyPair = Algorithm.ImportKeyPair(blobOfKeyPair); // Check the key size. if (keyPublic.KeySize != keyPair.KeySize) { SignVerifyText.Text += "ImportKeyPair failed! The imported key's size did not match the original's!"; return; } SignVerifyText.Text += " Key pair was successfully imported.\n"; }
public void createAsymmetricKeyPair( String strAsymmetricAlgName, UInt32 keyLength, out IBuffer buffPublicKey) { // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName); // Demonstrate use of the AlgorithmName property (not necessary to create a key pair). String strAlgName = objAlgProv.AlgorithmName; // Create an asymmetric key pair. CryptographicKey keyPair = objAlgProv.CreateKeyPair(keyLength); // Export the public key to a buffer for use by others. buffPublicKey = keyPair.ExportPublicKey(); //public key to internal buffer DataContainer.senderPublicKey = buffPublicKey; // You should keep your private key (embedded in the key pair) secure. For // the purposes of this example, however, we're just copying it into a // static class variable for later use during decryption. DataContainer.senderKeyPair = keyPair.Export(); }
/// <summary> /// Вызывается при обычном запуске приложения пользователем. Будут использоваться другие точки входа, /// например, если приложение запускается для открытия конкретного файла. /// </summary> /// <param name="e">Сведения о запросе и обработке запуска.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Не повторяйте инициализацию приложения, если в окне уже имеется содержимое, // только обеспечьте активность окна if (rootFrame == null) { // Создание фрейма, который станет контекстом навигации, и переход к первой странице rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Загрузить состояние из ранее приостановленного приложения } // Размещение фрейма в текущем окне Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // Если стек навигации не восстанавливается для перехода к первой странице, // настройка новой страницы путем передачи необходимой информации в качестве параметра // параметр string keypairfilename = ApplicationData.Current.LocalFolder.Path + "\\" + GlobalVars.HardWareID + ".001"; if (!File.Exists(keypairfilename)) { string RSAProvName = AsymmetricAlgorithmNames.RsaPkcs1; AsymmetricKeyAlgorithmProvider RSAProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(RSAProvName); CryptographicKey ClientKeyPair = RSAProv.CreateKeyPair(2048); byte[] ClientKeyPairBytes = ClientKeyPair.Export().ToArray(); File.WriteAllBytes(keypairfilename, ClientKeyPairBytes); } if (IsLicenseValid()) { rootFrame.Navigate(typeof(StartPage), e.Arguments); } else { rootFrame.Navigate(typeof(Registration), e.Arguments); } } // Обеспечение активности текущего окна Window.Current.Activate(); } }
public void CreateKey(KeySize keySize = KeySize.KS2048) { AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey key = asym.CreateKeyPair((uint)keySize); var privateKey = key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey); var publicKey = key.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); //System.Diagnostics.Debug.WriteLine($"private : {BitConverter.ToString(privateKey.ToArray())}"); //System.Diagnostics.Debug.WriteLine($"public : {BitConverter.ToString(publicKey.ToArray())}"); PublicKey = new PublicKey(publicKey); PrivateKey = new PrivateKey(privateKey); }
public static RSAKey GenerateKeys() { CryptographicKey key = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1).CreateKeyPair(2048); byte[] privateKey; byte[] publicKey; CryptographicBuffer.CopyToByteArray(key.Export(CryptographicPrivateKeyBlobType.Capi1PrivateKey), out privateKey); CryptographicBuffer.CopyToByteArray(key.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey), out publicKey); RSAKey RSAKey = new RSAKey(); RSAKey.PrivateKey = privateKey; RSAKey.PublicKey = publicKey; return(RSAKey); }
public static AsymmetricCipherKeyPair GetRsaKeyPair(CryptographicKey key) { var privateKeyBuffer = key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey); byte[] privateKeyBytes; CryptographicBuffer.CopyToByteArray(privateKeyBuffer, out privateKeyBytes); var asn1 = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyBytes); var rsa = new RsaPrivateKeyStructure(asn1); var pubKey = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); var privKey = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); return(new AsymmetricCipherKeyPair(pubKey, privKey)); }
public RawRsa(CryptographicKey key) { IBuffer buf = key.Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey); byte[] blob; CryptographicBuffer.CopyToByteArray(buf, out blob); var m = new Marshaller(blob, DataRepresentation.LittleEndian); var header = m.Get <BCryptRsaKeyBlob>(); E = FromBigEndian(m.GetArray <byte>((int)header.cbPublicExp)); N = FromBigEndian(m.GetArray <byte>((int)header.cbModulus)); P = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); Q = FromBigEndian(m.GetArray <byte>((int)header.cbPrime2)); DP = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); DQ = FromBigEndian(m.GetArray <byte>((int)header.cbPrime2)); InverseQ = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); D = FromBigEndian(m.GetArray <byte>((int)header.cbModulus)); }
public static Tuple <string, string> WinRTCreateKeyPair() { AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey key = asym.CreateKeyPair(1024); IBuffer privateKeyBuffer = key.Export(CryptographicPrivateKeyBlobType.Capi1PrivateKey); IBuffer publicKeyBuffer = key.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey); byte[] privateKeyBytes; byte[] publicKeyBytes; CryptographicBuffer.CopyToByteArray(privateKeyBuffer, out privateKeyBytes); CryptographicBuffer.CopyToByteArray(publicKeyBuffer, out publicKeyBytes); string privateKey = Convert.ToBase64String(privateKeyBytes); string publicKey = Convert.ToBase64String(publicKeyBytes); return(new Tuple <string, string>(privateKey, publicKey)); }
public void createAsymmetricKeyPair( String strAsymmetricAlgName, UInt32 keyLength, out IBuffer buffPublicKey) { // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName); // Demonstrate use of the AlgorithmName property (not necessary to create a key pair). String strAlgName = objAlgProv.AlgorithmName; // Create an asymmetric key pair. keyPair = objAlgProv.CreateKeyPair(keyLength); // Export the public key to a buffer for use by others. buffPublicKey = keyPair.ExportPublicKey(); keys = keyPair.Export(); }
/// <summary> /// Generates new key pair using OS CSP /// </summary> /// <param name="numBits"></param> /// <param name="publicExponent"></param> public RawRsa(int numBits, int publicExponent = 65537) { AsymmetricKeyAlgorithmProvider prov = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256); CryptographicKey key = prov.CreateKeyPair((uint)numBits); IBuffer buf = key.Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey); byte[] blob; CryptographicBuffer.CopyToByteArray(buf, out blob); var m = new Marshaller(blob, DataRepresentation.LittleEndian); var header = m.Get <BCryptRsaKeyBlob>(); E = FromBigEndian(m.GetArray <byte>((int)header.cbPublicExp)); N = FromBigEndian(m.GetArray <byte>((int)header.cbModulus)); P = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); Q = FromBigEndian(m.GetArray <byte>((int)header.cbPrime2)); DP = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); DQ = FromBigEndian(m.GetArray <byte>((int)header.cbPrime2)); InverseQ = FromBigEndian(m.GetArray <byte>((int)header.cbPrime1)); D = FromBigEndian(m.GetArray <byte>((int)header.cbModulus)); }
async public Task CreateAsymmetricKey() { AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey cryptographicKeyASymetric = provider.CreateKeyPair(512); buffPublicKey = cryptographicKeyASymetric.ExportPublicKey(); IBuffer buffKeyPair = cryptographicKeyASymetric.Export(); await KnownFolders.PicturesLibrary.CreateFileAsync("PrivateKey.txt", CreationCollisionOption.ReplaceExisting); StorageFile storageFile = await KnownFolders.PicturesLibrary.GetFileAsync("PrivateKey.txt"); await FileIO.WriteBufferAsync(storageFile, buffKeyPair); T2.Text = "buffPublicKey64: " + CryptographicBuffer.EncodeToBase64String(buffPublicKey); T3.Text = "buffPublicKeyHex: " + CryptographicBuffer.EncodeToHexString(buffPublicKey); T4.Text = "(Private Key) buffKeyPair64: " + CryptographicBuffer.EncodeToBase64String(buffKeyPair); T5.Text = "(Private Key) buffKeyPairHex: " + CryptographicBuffer.EncodeToHexString(buffKeyPair); }
public RSAParameters ExportParameters(bool includePrivateParameters) { #if WINDOWS_STORE IBuffer export = keyPair.Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey); byte[] result; CryptographicBuffer.CopyToByteArray(export, out result); BCryptRsaKeyBlob header = BCryptRsaKeyBlob.Load(result); int offset = Marshal.SizeOf <BCryptRsaKeyBlob>(); byte[] exponent = result.Skip(offset).Take((int)header.cbPublicExp).ToArray(); offset += (int)header.cbPublicExp; byte[] modulus = result.Skip(offset).Take((int)header.cbModulus).ToArray(); return(new RSAParameters(exponent, modulus)); #else System.Security.Cryptography.RSAParameters parameters = provider.ExportParameters(includePrivateParameters); return(new RSAParameters(parameters.Exponent, parameters.Modulus)); #endif }
/// <summary> /// This is the click handler for the 'RunSample' button. It is responsible for executing the sample code. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunSample_Click(object sender, RoutedEventArgs e) { String algName = AlgorithmNames.SelectionBoxItem.ToString(); UInt32 KeySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString()); Scenario7Text.Text = ""; IBuffer Data; String cookie = "Some cookie to encrypt"; switch (AlgorithmNames.SelectedIndex) { case 0: Data = CryptographicBuffer.ConvertStringToBinary(cookie, BinaryStringEncoding.Utf16LE); break; // OAEP Padding depends on key size, message length and hash block length // // The maximum plaintext length is KeyLength - 2*HashBlock - 2 // // OEAP padding supports an optional label with the length is restricted by plaintext/key/hash sizes. // Here we just use a small label. case 1: Data = CryptographicBuffer.GenerateRandom(1024 / 8 - 2 * 20 - 2); break; case 2: Data = CryptographicBuffer.GenerateRandom(1024 / 8 - 2 * (256 / 8) - 2); break; case 3: Data = CryptographicBuffer.GenerateRandom(2048 / 8 - 2 * (384 / 8) - 2); break; case 4: Data = CryptographicBuffer.GenerateRandom(2048 / 8 - 2 * (512 / 8) - 2); break; default: Scenario7Text.Text += "An invalid algorithm was selected"; return; } IBuffer Encrypted; IBuffer Decrypted; IBuffer blobOfPublicKey; IBuffer blobOfKeyPair; // Crate an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input. AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); Scenario7Text.Text += "*** Sample Encryption Algorithm\n"; Scenario7Text.Text += " Algorithm Name: " + Algorithm.AlgorithmName + "\n"; Scenario7Text.Text += " Key Size: " + KeySize + "\n"; // Generate a random key. CryptographicKey keyPair = Algorithm.CreateKeyPair(KeySize); // Encrypt the data. try { Encrypted = CryptographicEngine.Encrypt(keyPair, Data, null); } catch (ArgumentException ex) { Scenario7Text.Text += ex.Message + "\n"; Scenario7Text.Text += "An invalid key size was selected for the given algorithm.\n"; return; } Scenario7Text.Text += " Plain text: " + Data.Length + " bytes\n"; Scenario7Text.Text += " Encrypted: " + Encrypted.Length + " bytes\n"; // Export the public key. blobOfPublicKey = keyPair.ExportPublicKey(); blobOfKeyPair = keyPair.Export(); // Import the public key. CryptographicKey keyPublic = Algorithm.ImportPublicKey(blobOfPublicKey); if (keyPublic.KeySize != keyPair.KeySize) { Scenario7Text.Text += "ImportPublicKey failed! The imported key's size did not match the original's!"; return; } // Import the key pair. keyPair = Algorithm.ImportKeyPair(blobOfKeyPair); // Check the key size of the imported key. if (keyPublic.KeySize != keyPair.KeySize) { Scenario7Text.Text += "ImportKeyPair failed! The imported key's size did not match the original's!"; return; } // Decrypt the data. Decrypted = CryptographicEngine.Decrypt(keyPair, Encrypted, null); if (!CryptographicBuffer.Compare(Decrypted, Data)) { Scenario7Text.Text += "Decrypted data does not match original!"; return; } }
private static async void StoreRsaKey(CryptographicKey key, CryptographicKey aesKey) { await StorageInterface.WriteBufferToRoamingFolder("PWM/RsaKey", EncryptAes(aesKey, key.Export())); }