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"; }
/// <summary> /// Checks directory for keys and returns a boolean /// /// true = keys exists /// false = keys do not exists /// /// </summary> /// <returns></returns> private static async System.Threading.Tasks.Task <bool> checkKeysDirectory() { // read keypair for sender if it exists StorageFolder localFolder = ApplicationData.Current.LocalFolder; try { StorageFile senderKeyPair = await localFolder.GetFileAsync(DataContainer.User + ".KeyPair"); if (senderKeyPair != null) { string keyPairText = await FileIO.ReadTextAsync(senderKeyPair); // buffer from text DataContainer.senderKeyPair = decode64BaseString(keyPairText); // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName); // Import the public key from a buffer. CryptographicKey keyPair = objAlgProv.ImportKeyPair(DataContainer.senderKeyPair); DataContainer.senderPublicKey = keyPair.ExportPublicKey(); return(true); } } catch (System.IO.FileNotFoundException ex) { Debug.WriteLine(ex.ToString()); } return(false); }
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(); }
// ------------ KEYPAIRS, ENCRYPTION and DECRYPTION --------------- public void generateNewKeyPair() { #if NETFX_CORE // Create an asymmetric key pair. UInt32 keyLength = 2048; // This is a must because of the algorithm that we currently use myKeyPair = objAlgProv.CreateKeyPair(keyLength); // Export the public key to a buffer for use by others. IBuffer buffPublicKey = myKeyPair.ExportPublicKey(); myPublicKeyString = cryptoBufferToString(buffPublicKey); Debug.Log("NOVI KLJUC: |" + myPublicKeyString + "|"); #endif }
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); }
/// <summary> /// Create a new random software key (public and private) matching the parameters in keyParams. /// </summary> /// <param name="keyParams"></param> /// <returns></returns> public AsymCryptoSystem(TpmPublic keyParams) { TpmAlgId keyAlgId = keyParams.type; PublicParms = keyParams.Copy(); switch (keyAlgId) { case TpmAlgId.Rsa: { var rsaParams = keyParams.parameters as RsaParms; AsymmetricKeyAlgorithmProvider RsaProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256); Key = RsaProvider.CreateKeyPair(rsaParams.keyBits); IBuffer keyBlobBuffer = Key.ExportPublicKey(CryptographicPublicKeyBlobType.BCryptPublicKey); byte[] blob; CryptographicBuffer.CopyToByteArray(keyBlobBuffer, out blob); var m = new Marshaller(blob, DataRepresentation.LittleEndian); var header = m.Get <BCryptRsaKeyBlob>(); var modulus = m.GetArray <byte>((int)header.cbModulus); var pubId = new Tpm2bPublicKeyRsa(modulus); PublicParms.unique = pubId; break; } case TpmAlgId.Ecc: { var eccParms = keyParams.parameters as EccParms; var alg = RawEccKey.GetEccAlg(keyParams); if (alg == null) { Globs.Throw <ArgumentException>("Unknown ECC curve"); return; } AsymmetricKeyAlgorithmProvider EccProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(alg); Key = EccProvider.CreateKeyPair((uint)RawEccKey.GetKeyLength(eccParms.curveID)); break; } default: Globs.Throw <ArgumentException>("Algorithm not supported"); break; } }
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(); }
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 static string getPreGeneratedPublicKey(CryptographicKey keyPair) { return(CryptographicBuffer.EncodeToBase64String(keyPair.ExportPublicKey())); //key(buffer)->string }
/// <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; } }