public void TestAsymmetricEncryptionNonPersistedKey() { byte[] plainBytes = ByteUtil.Utf8NoBOM.GetBytes("Secret String For Testing"); AsymmetricEncryption.GenerateNewKeys(out string publicKey, out string privateKey); byte[] encryptedBytes = AsymmetricEncryption.EncryptWithKey(publicKey, plainBytes); Assert.IsFalse(ByteUtil.ByteArraysMatch(plainBytes, encryptedBytes)); byte[] decryptedBytes = AsymmetricEncryption.DecryptWithKey(privateKey, encryptedBytes); Assert.IsTrue(ByteUtil.ByteArraysMatch(plainBytes, decryptedBytes)); // Try encrypting with the private key (usually done with only the public key). byte[] encryptedBytes2 = AsymmetricEncryption.EncryptWithKey(privateKey, plainBytes); Assert.IsFalse(ByteUtil.ByteArraysMatch(plainBytes, encryptedBytes2)); // Try decrypting with the public key (should fail) try { byte[] decryptedBytes2 = AsymmetricEncryption.DecryptWithKey(publicKey, encryptedBytes); Assert.Fail("Expected exception when trying to decrypt with public key."); } catch { } // Verify that private-key-encryption worked as intended byte[] decryptedBytes3 = AsymmetricEncryption.DecryptWithKey(privateKey, encryptedBytes); Assert.IsTrue(ByteUtil.ByteArraysMatch(plainBytes, decryptedBytes3)); }
private void TestRSAPayloadSizeLimitAtKeySize(int keySize, int expectedPayloadSizeLimit, int startTestAt = -1) { AsymmetricKeypair keys = GetStaticKeys(keySize); if (startTestAt < 1) { startTestAt = expectedPayloadSizeLimit; } int expectedFailureAt = expectedPayloadSizeLimit + 1; for (int i = startTestAt; i <= expectedFailureAt; i++) { byte[] plainBytes = new byte[i]; SecureRandom.NextBytes(plainBytes); byte[] encryptedBytes = null; try { encryptedBytes = AsymmetricEncryption.EncryptWithKey(keys.publicKey, plainBytes); } catch (Exception ex) { if (i == expectedFailureAt) { return; } Assert.Fail(keySize + "-bit key failed at payload size " + i + " bytes. Expected failure at " + expectedFailureAt + "-byte payload size. Exception: " + ex.ToString()); } if (i == expectedFailureAt) { Assert.Fail("Expected exception when encrypting " + expectedFailureAt + "-byte payload size. Did not get exception. " + keySize + "-bit key test failed."); } Assert.IsFalse(ByteUtil.ByteArraysMatch(plainBytes, encryptedBytes)); byte[] decryptedBytes = AsymmetricEncryption.DecryptWithKey(keys.privateKey, encryptedBytes); Assert.IsTrue(ByteUtil.ByteArraysMatch(plainBytes, decryptedBytes)); } }