/// <summary> /// Initialize this class /// </summary> /// /// <param name="Parameters">The cipher Parameters</param> /// <param name="KeyPair">The public or private key</param> /// <param name="Tag">An identity field</param> /// /// <exception cref="CryptoAsymmetricException">Thrown if an invalid key is used</exception> public AsymmetricContainer(IAsymmetricParameters Parameters, IAsymmetricKeyPair KeyPair, byte[] Tag = null) { if (!(KeyPair is IAsymmetricKeyPair)) throw new CryptoAsymmetricException("KeyContainer:Ctor", "Not a valid key-pair!", new InvalidDataException()); _publicKey = KeyPair.PublicKey; _privateKey = KeyPair.PrivateKey; _asmParameters = Parameters; _idTag = Tag; }
private void PopulateDsaKeys() { IAsymmetricKeyPair dsaKeyPair = dsaKeyProvider.CreateKeyPair(2048); string firstPublicKey = pkcs8PemFormatter.GetAsPem(dsaKeyPair.PublicKey); string firstPrivateKey = pkcs8PemFormatter.GetAsPem(dsaKeyPair.PrivateKey); files.Add("private.dsa.first", encoding.GetBytes(firstPrivateKey)); files.Add("public.dsa.first", encoding.GetBytes(firstPublicKey)); dsaKeyPair = dsaKeyProvider.CreateKeyPair(2048); string secondPublicKey = pkcs8PemFormatter.GetAsPem(dsaKeyPair.PublicKey); string secondPrivateKey = pkcs8PemFormatter.GetAsPem(dsaKeyPair.PrivateKey); files.Add("private.dsa.second", encoding.GetBytes(secondPrivateKey)); files.Add("public.dsa.second", encoding.GetBytes(secondPublicKey)); }
public void Setup() { var rsaKeyProvider = new RsaKeyProvider(keyPairGenerator); IAsymmetricKeyPair keyPair = rsaKeyProvider.CreateKeyPair(2048); key = keyPair.PublicKey; string keyContent = provider.GetRsaPublicKeyContent(key); result = base64.FromBase64String(keyContent); using (var stream = new MemoryStream(result)) { rawHeader = ReadNextContent(stream); rawExponent = ReadNextContent(stream); rawModulus = ReadNextContent(stream); } }
public static void TestSignVerifyNormalization() { IAsymmetricKeyPair keyPair = New <IAsymmetricFactory>().CreateKeyPair(512); Signer signer = new Signer(keyPair.PrivateKey); Verifier verifier = new Verifier(keyPair.PublicKey); byte[] signature; signature = signer.Sign("A", "simple", "string"); Assert.That(verifier.Verify(signature, "A simple string")); signature = signer.Sign("Asimplestring"); Assert.That(verifier.Verify(signature, "A simple string")); signature = signer.Sign(" A simple string "); Assert.That(verifier.Verify(signature, " A \r\nsimple\t string")); }
public void Setup() { keyPair = Mock.Of <IAsymmetricKeyPair>(); keyProvider = new Mock <IElGamalKeyProvider>(); keyProvider.Setup(kp => kp.CreateKeyPair(2048, true)) .Returns(keyPair); console = new Mock <ConsoleWrapper>(); commandHandler = new CreateElGamalKeyCommandHandler(keyProvider.Object, console.Object); command = new CreateKeyCommand <ElGamalKey> { KeySize = 2048, UseRfc3526Prime = true }; commandHandler.Execute(command); }
/// <summary> /// Initialize the cipher. /// <para>Requires a <see cref="MPKCPublicKey"/> for encryption, or a <see cref="MPKCPrivateKey"/> for decryption</para> /// </summary> /// /// <param name="Encryption">When true cipher is for encryption, if false, decryption</param> /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the McEliece public or private key</param> /// /// <exception cref="MPKCException">Thrown if the cipher is not initialized or the key is invalid</exception> public void Initialize(bool Encryption, IAsymmetricKeyPair KeyPair) { if (!(KeyPair is MPKCKeyPair)) { throw new MPKCException("MPKCEncrypt:Initialize", "Not a valid McEliece key pair!", new InvalidOperationException()); } // init implementation engine _encEngine.Initialize(Encryption, KeyPair); // get the sizes if (Encryption) { if (KeyPair.PublicKey == null) { throw new MPKCException("MPKCEncrypt:Initialize", "Encryption requires a public key!", new InvalidOperationException()); } if (!(KeyPair.PublicKey is MPKCPublicKey)) { throw new MPKCException("MPKCEncrypt:Initialize", "The public key is invalid!", new ArgumentException()); } MPKCPublicKey pub = (MPKCPublicKey)KeyPair.PublicKey; _maxCipherText = pub.N >> 3; _maxPlainText = pub.K >> 3; } else { if (KeyPair.PrivateKey == null) { throw new MPKCException("MPKCEncrypt:Initialize", "Decryption requires a private key!", new InvalidOperationException()); } if (!(KeyPair.PrivateKey is MPKCPrivateKey)) { throw new MPKCException("MPKCEncrypt:Initialize", "The private key is invalid!", new ArgumentException()); } MPKCPrivateKey pri = (MPKCPrivateKey)KeyPair.PrivateKey; _maxPlainText = pri.K >> 3; _maxCipherText = pri.N >> 3; } _isInitialized = true; }
public string Decrypt(IAsymmetricKeyPair privateKey, byte[] encryptedText) { var splitArray = encryptedText.Select((x, i) => new { Key = i / EncryptedTextSize, Value = x }) .GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray()) .ToArray(); var decryptedText = ""; foreach (var bytes in splitArray) { using (var cipher = new NTRUEncrypt(this.encParams)) { cipher.Initialize(privateKey); var dec = cipher.Decrypt(bytes); decryptedText += Encoding.UTF8.GetString(dec); } } return(decryptedText); }
/// <summary> /// Convert an external representation of a key-pair to an internal representation that is suitable for actual use. /// </summary> /// <param name="accountKey">The account key.</param> /// <param name="passphrase">The passphrase to decrypt the private key, if any, with.</param> /// <returns>A UserKeyPair or null if it was not possible to decrypt it.</returns> public static UserKeyPair ToUserKeyPair(this Api.Model.AccountKey accountKey, Passphrase passphrase) { if (accountKey == null) { throw new ArgumentNullException(nameof(accountKey)); } string privateKeyPem = DecryptPrivateKeyPem(accountKey.KeyPair.PrivateEncryptedPem, passphrase); if (privateKeyPem == null) { return(null); } IAsymmetricKeyPair keyPair = Resolve.AsymmetricFactory.CreateKeyPair(accountKey.KeyPair.PublicPem, privateKeyPem); UserKeyPair userAsymmetricKeys = new UserKeyPair(EmailAddress.Parse(accountKey.User), accountKey.Timestamp, keyPair); return(userAsymmetricKeys); }
static double SignTest(int Iterations, RNBWParameters Param, bool Sign = true) { Stopwatch runTimer = new Stopwatch(); byte[] code; RNBWKeyGenerator mkgen = new RNBWKeyGenerator(Param, new CTRPrng(BlockCiphers.RDX, SeedGenerators.CSPRsg, 16384, 16)); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] data = new byte[200]; new CSPRng().GetBytes(data); using (RNBWSign sgn = new RNBWSign(Param)) { if (Sign) { sgn.Initialize(akp.PrivateKey); runTimer.Start(); for (int i = 0; i < Iterations; i++) { code = sgn.Sign(data, 0, data.Length); } runTimer.Stop(); } else { // sign the array first sgn.Initialize(akp.PrivateKey); code = sgn.Sign(data, 0, data.Length); // init for verify sgn.Initialize(akp.PublicKey); runTimer.Start(); for (int i = 0; i < Iterations; i++) { sgn.Verify(data, 0, data.Length, code); } runTimer.Stop(); } } return(runTimer.Elapsed.TotalMilliseconds); }
public async Task TestCreateAndLoadAsymmetricKeysStore() { FakeDataStore.AddFolder(@"C:\Temp"); IDataContainer workFolder = New <IDataContainer>(@"C:\Temp\"); AccountStorage store = new AccountStorage(new LocalAccountService(new LogOnIdentity(EmailAddress.Parse(@"*****@*****.**"), new Passphrase("secret")), workFolder)); UserKeyPair userKeyPair = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); await store.ImportAsync(userKeyPair); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PrivateKey, Is.Not.Null); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PublicKey, Is.Not.Null); IAsymmetricKeyPair keyPair = (await store.AllKeyPairsAsync()).First().KeyPair; store = new AccountStorage(new LocalAccountService(new LogOnIdentity(EmailAddress.Parse(@"*****@*****.**"), new Passphrase("secret")), workFolder)); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PrivateKey.ToString(), Is.EqualTo(keyPair.PrivateKey.ToString())); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PublicKey.ToString(), Is.EqualTo(keyPair.PublicKey.ToString())); }
public bool VerifyKeyPair(IAsymmetricKeyPair keyPair) { ECPrivateKeyParameters privateKey; ECPublicKeyParameters publicKey; try { privateKey = GetKeyParameter <ECPrivateKeyParameters>(keyPair.PrivateKey?.Content, AsymmetricKeyType.Private); publicKey = GetKeyParameter <ECPublicKeyParameters>(keyPair.PublicKey?.Content, AsymmetricKeyType.Public); } catch (CryptographicException) { return(false); } return(privateKey.Parameters.Equals(publicKey.Parameters) && publicKey.Parameters.Curve.A.FieldName == privateKey.Parameters.Curve.A.FieldName && publicKey.Q.Equals(privateKey.Parameters.G.Multiply(privateKey.D))); }
public void SetupFormattingProviderTest() { var secureRandom = new SecureRandomGenerator(); rsaKeyProvider = new RsaKeyProvider(new AsymmetricKeyPairGenerator(secureRandom)); keyPair = rsaKeyProvider.CreateKeyPair(2048); var oidMapper = new OidToCipherTypeMapper(); var asymmetricKeyConverter = new AsymmetricKeyProvider(oidMapper, new KeyInfoWrapper(), rsaKeyProvider, null, null, null); pkcs8PemFormattingProvider = new Pkcs8PemFormattingProvider(asymmetricKeyConverter); var configuration = Mock.Of <IConfiguration>(m => m.Get <int>("SaltLengthInBytes") == 100 && m.Get <int>("KeyDerivationIterationCount") == 1); var encryptionProvider = new KeyEncryptionProvider(configuration, secureRandom, asymmetricKeyConverter, new Pkcs12KeyEncryptionGenerator(), new AesKeyEncryptionGenerator()); pkcsEncryptedKey = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "password", EncryptionType.Pkcs); aesEncryptedKey = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "password", EncryptionType.Aes); }
public bool VerifyKeyPair(IAsymmetricKeyPair keyPair) { DsaPrivateKeyParameters privateKey; DsaPublicKeyParameters publicKey; try { publicKey = GetKeyParameter <DsaPublicKeyParameters>(keyPair.PublicKey?.Content, AsymmetricKeyType.Public); privateKey = GetKeyParameter <DsaPrivateKeyParameters>(keyPair.PrivateKey?.Content, AsymmetricKeyType.Private); } catch (CryptographicException) { return(false); } return(privateKey.X.BitCount > 0 && publicKey.Y.BitCount > 0 && privateKey.Parameters.Equals(publicKey.Parameters) && publicKey.Y.Equals(publicKey.Parameters.G.ModPow(privateKey.X, publicKey.Parameters.P))); }
/// <summary> /// Initialize the cipher. /// <para>Requires a <see cref="MPKCPublicKey"/> for encryption, or a <see cref="MPKCPrivateKey"/> for decryption</para> /// </summary> /// /// <param name="Encryption">When true cipher is for encryption, if false, decryption</param> /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the McEliece public or private key</param> public void Initialize(bool Encryption, IAsymmetricKeyPair KeyPair) { _isEncryption = Encryption; _keyPair = KeyPair; if (_isEncryption) { _secRnd = GetPrng(_cipherParams.RandomEngine); _N = ((MPKCPublicKey)KeyPair.PublicKey).N; _K = ((MPKCPublicKey)KeyPair.PublicKey).K; _T = ((MPKCPublicKey)KeyPair.PublicKey).T; _maxPlainText = (((MPKCPublicKey)KeyPair.PublicKey).K >> 3); } else { _N = ((MPKCPrivateKey)KeyPair.PrivateKey).N; _K = ((MPKCPrivateKey)KeyPair.PrivateKey).K; _T = ((MPKCPrivateKey)KeyPair.PrivateKey).T; } }
private bool TryParseNonces(IAsymmetricKeyPair keyPair, List <Message> requestedContactsMessages) { foreach (var message in requestedContactsMessages) { try { var encryptedNonce = new TryteString( message.Payload.Value.Substring( message.Payload.Value.IndexOf(Constants.LineBreak.Value, StringComparison.Ordinal) + Constants.LineBreak.TrytesLength)); var nonce = this.Encryption.Decrypt(keyPair, encryptedNonce.ToBytes()); return(DateTime.TryParse(Encoding.UTF8.GetString(nonce), out _)); } catch { // ignored } } return(false); }
static void FullCycle(RLWEParameters Param) { RLWEKeyGenerator mkgen = new RLWEKeyGenerator(Param); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] enc; using (RLWEEncrypt mpe = new RLWEEncrypt(Param)) { mpe.Initialize(akp.PublicKey); byte[] data = new byte[mpe.MaxPlainText]; enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Compare.AreEqual(dec, data)) { throw new Exception("Encryption test: decryption failure!"); } } }
static void FullCycle() { MPKCParameters mpar = MPKCParamSets.MPKCFM11T40S256; //APR2011743FAST MPKCKeyGenerator mkgen = new MPKCKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] enc; using (MPKCEncrypt mpe = new MPKCEncrypt(mpar)) { mpe.Initialize(akp.PublicKey); byte[] data = new byte[mpe.MaxPlainText]; enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Compare.AreEqual(dec, data)) { throw new Exception("Encryption test: decryption failure!"); } } }
public static void TestGetSetRecipientsAndClone() { V2AsymmetricRecipientsEncryptedHeaderBlock headerBlock = new V2AsymmetricRecipientsEncryptedHeaderBlock(new V2AesCrypto(SymmetricKey.Zero256, SymmetricIV.Zero128, 0)); IAsymmetricKeyPair aliceKeyPair = New <IAsymmetricFactory>().CreateKeyPair(512); IAsymmetricKeyPair bobKeyPair = New <IAsymmetricFactory>().CreateKeyPair(512); List <UserPublicKey> publicKeys = new List <UserPublicKey>(); publicKeys.Add(new UserPublicKey(EmailAddress.Parse("*****@*****.**"), aliceKeyPair.PublicKey)); publicKeys.Add(new UserPublicKey(EmailAddress.Parse("*****@*****.**"), bobKeyPair.PublicKey)); Recipients recipients = new Recipients(publicKeys); headerBlock.Recipients = recipients; Assert.That(headerBlock.Recipients.PublicKeys.ToList()[0].Email, Is.EqualTo(EmailAddress.Parse("*****@*****.**"))); Assert.That(headerBlock.Recipients.PublicKeys.ToList()[1].Email, Is.EqualTo(EmailAddress.Parse("*****@*****.**"))); V2AsymmetricRecipientsEncryptedHeaderBlock clone = (V2AsymmetricRecipientsEncryptedHeaderBlock)headerBlock.Clone(); Assert.That(clone.Recipients.PublicKeys.ToList()[0].Email, Is.EqualTo(EmailAddress.Parse("*****@*****.**"))); Assert.That(clone.Recipients.PublicKeys.ToList()[0].PublicKey.ToString(), Is.EqualTo(aliceKeyPair.PublicKey.ToString())); Assert.That(clone.Recipients.PublicKeys.ToList()[1].Email, Is.EqualTo(EmailAddress.Parse("*****@*****.**"))); Assert.That(clone.Recipients.PublicKeys.ToList()[1].PublicKey.ToString(), Is.EqualTo(bobKeyPair.PublicKey.ToString())); }
static void FullCycle() { NTRUParameters mpar = NTRUParamSets.APR2011439FAST; //APR2011743FAST NTRUKeyGenerator mkgen = new NTRUKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] enc; using (NTRUEncrypt mpe = new NTRUEncrypt(mpar)) { mpe.Initialize(akp.PublicKey); byte[] data = new byte[mpe.MaxPlainText]; enc = mpe.Encrypt(data); mpe.Initialize(akp); byte[] dec = mpe.Decrypt(enc); if (!Compare.AreEqual(dec, data)) { throw new Exception("Тест шифрования: отказ дешифрования!"); } } }
static double Encrypt(int Iterations, NTRUParameters Param) { NTRUKeyGenerator mkgen = new NTRUKeyGenerator(Param); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] ptext = new CSPRng().GetBytes(64); byte[] ctext; Stopwatch runTimer = new Stopwatch(); using (NTRUEncrypt mpe = new NTRUEncrypt(Param)) { mpe.Initialize(akp.PublicKey); runTimer.Start(); for (int i = 0; i < Iterations; i++) { ctext = mpe.Encrypt(ptext); } runTimer.Stop(); } return(runTimer.Elapsed.TotalMilliseconds); }
/// <summary> /// Decrypts a byte array /// </summary> /// <param name="keyPair">The correct key pair</param> /// <param name="encryptedBytes">The encrypted byte array</param> /// <returns>Decrypted string</returns> public byte[] Decrypt(IAsymmetricKeyPair keyPair, byte[] encryptedBytes) { var splitArray = encryptedBytes.Select((x, i) => new { Key = i / this.maxEncryptionSize, Value = x }) .GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray()).ToArray(); var bytesList = new List <byte[]>(); foreach (var bytes in splitArray) { using (var cipher = new NTRUEncrypt(this.ntruParameters)) { try { cipher.Initialize(keyPair); bytesList.Add(cipher.Decrypt(bytes)); } catch { // ignored } } } return(bytesList.SelectMany(a => a).ToArray()); }
/// <summary> /// Initialize the cipher. /// <para>Requires a <see cref="MPKCPublicKey"/> for encryption, or a <see cref="MPKCPrivateKey"/> for decryption</para> /// </summary> /// /// <param name="Encryption">When true cipher is for encryption, if false, decryption</param> /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the McEliece public or private key</param> /// /// <exception cref="MPKCException">Thrown if the cipher is not initialized or the key is invalid</exception> public void Initialize(bool Encryption, IAsymmetricKeyPair KeyPair) { if (!(KeyPair is MPKCKeyPair)) throw new MPKCException("MPKCEncrypt:Initialize", "Not a valid McEliece key pair!", new InvalidOperationException()); // init implementation engine _encEngine.Initialize(Encryption, KeyPair); // get the sizes if (Encryption) { if (KeyPair.PublicKey == null) throw new MPKCException("MPKCEncrypt:Initialize", "Encryption requires a public key!", new InvalidOperationException()); if (!(KeyPair.PublicKey is MPKCPublicKey)) throw new MPKCException("MPKCEncrypt:Initialize", "The public key is invalid!", new ArgumentException()); MPKCPublicKey pub = (MPKCPublicKey)KeyPair.PublicKey; _maxCipherText = pub.N >> 3; _maxPlainText = pub.K >> 3; } else { if (KeyPair.PrivateKey == null) throw new MPKCException("MPKCEncrypt:Initialize", "Decryption requires a private key!", new InvalidOperationException()); if (!(KeyPair.PrivateKey is MPKCPrivateKey)) throw new MPKCException("MPKCEncrypt:Initialize", "The private key is invalid!", new ArgumentException()); MPKCPrivateKey pri = (MPKCPrivateKey)KeyPair.PrivateKey; _maxPlainText = pri.K >> 3; _maxCipherText = pri.N >> 3; } _isInitialized = true; }
/// <summary> /// Initialize the cipher /// </summary> /// /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the McEliece public or private key</param> /// /// <exception cref="MPKCException">Thrown if an invalid keypair is used</exception> public void Initialize(IAsymmetricKeyPair KeyPair) { if (!(KeyPair is MPKCKeyPair)) throw new MPKCException("MPKCSign:Initialize", "The key pair is not a valid McEliece key pair!", new InvalidDataException()); Reset(); _keyPair = KeyPair; _isInitialized = true; }
/// <summary> /// Initialize the cipher for Decryption; This Initialize() method is only for Decryption. /// <para>Requires a <see cref="NTRUPublicKey"/> for encryption, or a <see cref="NTRUPrivateKey"/> for decryption contained in an <see cref="NTRUKeyPair"/> class. /// NTRU requires both Public and Private keys to decrypt a message. /// Use the <see cref="Initialize(IAsymmetricKey)"/> method and pass the NTRUPublicKey for Encryption. /// </para> /// </summary> /// /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the NTRU public or private key</param> /// /// <exception cref="CryptoAsymmetricException">Thrown if a key is invalid</exception> public void Initialize(IAsymmetricKeyPair KeyPair) { if (!(KeyPair is NTRUKeyPair)) throw new CryptoAsymmetricException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (KeyPair.PublicKey == null) throw new CryptoAsymmetricException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (!(KeyPair.PublicKey is NTRUPublicKey)) throw new CryptoAsymmetricException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (KeyPair.PrivateKey == null) throw new CryptoAsymmetricException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (!(KeyPair.PrivateKey is NTRUPrivateKey)) throw new CryptoAsymmetricException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); _keyPair = (NTRUKeyPair)KeyPair; _isEncryption = false; _isInitialized = true; }
public UserKeyPair(EmailAddress userEmail, DateTime timestamp, IAsymmetricKeyPair keyPair) { UserEmail = userEmail; Timestamp = timestamp; KeyPair = keyPair; }
public static List <ChatMessage> FilterChatMessages(IEnumerable <TryteString> trytes, NtruKex ntruKex, IAsymmetricKeyPair keyPair) { var chatMessages = new List <ChatMessage>(); foreach (var tryte in trytes) { try { var trytesString = tryte.ToString(); var indexBreak = trytesString.IndexOf("9CHIOTAYOURIOTACHATAPP9", StringComparison.Ordinal); var messageTrytes = new TryteString(trytesString.Substring(0, indexBreak)); var dateTrytes = new TryteString(trytesString.Substring(indexBreak + 23, trytesString.Length - indexBreak - 23)); // can only decrypt messages from other user (send with own public key)! var decryptedMessage = ntruKex.Decrypt(keyPair, messageTrytes.ToBytes()); var date = DateTime.Parse(dateTrytes.ToUtf8String()); var chatMessage = new ChatMessage { Message = decryptedMessage, Date = date }; chatMessages.Add(chatMessage); } catch { continue; } } return(chatMessages); }
/// <summary> /// Generat an asymmetric key-pair /// </summary> private IAsymmetricKeyPair GenerateAsymmetricKeyPair(IAsymmetricParameters Parameters) { using (IAsymmetricGenerator gen = GetAsymmetricGenerator(Parameters)) _authKeyPair = gen.GenerateKeyPair(); return (IAsymmetricKeyPair)_authKeyPair.Clone(); }
/// <summary> /// Send the servers Auth-Stage Asymmetric Public key; <see cref="IAsymmetricKey"/>, built using the PKE params id from the servers identity structure. /// <para>The packet header; <see cref="DtmPacket"/>, contains the message type, payload length, sequence number, and exchange state. /// The payload is the servers Auth-Stage asymmetric Public Key.</para> /// </summary> /// /// <returns>A raw packet containing the packet header, and the servers Auth-Stage asymmetric Public Key</returns> private MemoryStream CreatePreAuth() { // server asym params _srvAsmParams = GetAsymmetricParams(_srvIdentity.PkeId); // generate the servers auth-stage key pair _authKeyPair = GenerateAsymmetricKeyPair(_srvAsmParams); // serialize servers public key MemoryStream pbk = _authKeyPair.PublicKey.ToStream(); // stage completed _exchangeState = DtmExchangeFlags.PreAuth; return pbk; }
public FakeLicenseAuthority() { _keyPair = New <IAsymmetricFactory>().CreateKeyPair(512); }
private void TestEncode() { RLWEParameters mpar = RLWEParamSets.RLWEN256Q7681; RLWEKeyGenerator mkgen = new RLWEKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); RLWEPublicKey pub = (RLWEPublicKey)akp.PublicKey; byte[] enc = pub.ToBytes(); using (RLWEPublicKey pub2 = RLWEPublicKey.From(enc)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } } OnProgress(new TestEventArgs("Passed public key serialization")); MemoryStream pubstr = pub.ToStream(); using (RLWEPublicKey pub2 = RLWEPublicKey.From(pubstr)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } } pubstr.Dispose(); OnProgress(new TestEventArgs("Passed public key stream test")); RLWEPrivateKey pri = (RLWEPrivateKey)akp.PrivateKey; enc = pri.ToBytes(); using (RLWEPrivateKey pri2 = RLWEPrivateKey.From(enc)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } } OnProgress(new TestEventArgs("Passed private key serialization")); MemoryStream pristr = pri.ToStream(); using (RLWEPrivateKey pri2 = RLWEPrivateKey.From(pristr)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } } pristr.Dispose(); OnProgress(new TestEventArgs("Passed private key stream test")); using (RLWEEncrypt mpe = new RLWEEncrypt(mpar)) { mpe.Initialize(akp.PublicKey); int sz = mpe.MaxPlainText; byte[] data = new byte[sz]; new VTDev.Libraries.CEXEngine.Crypto.Prng.CSPRng().GetBytes(data); enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Compare.AreEqual(dec, data)) { throw new Exception("EncryptionKey: decryption failure!"); } OnProgress(new TestEventArgs("Passed encryption test")); } pri.Dispose(); pub.Dispose(); }
private void TestEncrypt() { MPKCParameters mpar = (MPKCParameters)MPKCParamSets.MPKCFM11T40S256.DeepCopy(); MPKCKeyGenerator mkgen = new MPKCKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] enc; // Fujisaki using (MPKCEncrypt mpe = new MPKCEncrypt(mpar)) { mpe.Initialize(akp.PublicKey); int sz = mpe.MaxPlainText - 1; byte[] data = new byte[sz]; new CSPPrng().GetBytes(data); enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Evaluate.AreEqual(dec, data)) { throw new Exception("Encryption test: decryption failure!"); } OnProgress(new TestEventArgs("Passed Fujisaki encryption test")); } // KobaraLmai using (MPKCEncrypt mpe = new MPKCEncrypt(mpar)) { mpar = (MPKCParameters)MPKCParamSets.MPKCFM11T40S256.DeepCopy(); mpe.Initialize(akp.PublicKey); int sz = mpe.MaxPlainText - 1; byte[] data = new byte[sz]; new VTDev.Libraries.CEXEngine.Crypto.Prng.CSPPrng().GetBytes(data); enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Evaluate.AreEqual(dec, data)) { throw new Exception("Encryption test: decryption failure!"); } OnProgress(new TestEventArgs("Passed KobaraImai encryption test")); } // Pointcheval using (MPKCEncrypt mpe = new MPKCEncrypt(mpar)) { mpar = (MPKCParameters)MPKCParamSets.MPKCFM11T40S256.DeepCopy(); mpe.Initialize(akp.PublicKey); int sz = mpe.MaxPlainText - 1; byte[] data = new byte[sz]; new VTDev.Libraries.CEXEngine.Crypto.Prng.CSPPrng().GetBytes(data); enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Evaluate.AreEqual(dec, data)) { throw new Exception("Encryption test: decryption failure!"); } OnProgress(new TestEventArgs("Passed Pointcheval encryption test")); } }
/// <summary> /// Initialize the cipher. /// <para>Requires a <see cref="NTRUPublicKey"/> for encryption, or a <see cref="NTRUPrivateKey"/> for decryption</para> /// </summary> /// /// <param name="Encryption">When true cipher is for encryption, if false, decryption</param> /// <param name="KeyPair">The <see cref="IAsymmetricKeyPair"/> containing the NTRU public or private key</param> /// /// <exception cref="NTRUException">Thrown if a key is invalid</exception> public void Initialize(bool Encryption, IAsymmetricKeyPair KeyPair) { if (!(KeyPair is NTRUKeyPair)) throw new NTRUException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); _keyPair = (NTRUKeyPair)KeyPair; if (_keyPair.PublicKey == null) throw new NTRUException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (!(_keyPair.PublicKey is NTRUPublicKey)) throw new NTRUException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (!Encryption) { if (_keyPair.PrivateKey == null) throw new NTRUException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); if (!(_keyPair.PrivateKey is NTRUPrivateKey)) throw new NTRUException("NTRUEncrypt:Initialize", "Not a valid NTRU key pair!", new InvalidDataException()); } _isInitialized = true; }
private async Task <List <Contact> > LoadContactsOnAddressAsync(Address contactAddress, IAsymmetricKeyPair keyPair) { var requestedContactsMessages = await this.Messenger.GetMessagesByAddressAsync(contactAddress); var contacts = new List <Contact>(); foreach (var message in requestedContactsMessages) { try { var contactPayload = message.Payload.GetChunk(0, message.Payload.Value.IndexOf(Constants.LineBreak.Value, StringComparison.Ordinal)); var decryptedPayload = this.Encryption.Decrypt(keyPair, contactPayload.ToBytes()); var value = Encoding.UTF8.GetString(decryptedPayload); contacts.Add(JsonConvert.DeserializeObject <Contact>(value)); } catch { // ignored, since invalid contact requests lead us here } } return(contacts); }
private void TestEncode() { MPKCParameters mpar = (MPKCParameters)MPKCParamSets.MPKCFM11T40S256.DeepCopy(); MPKCKeyGenerator mkgen = new MPKCKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); MPKCPublicKey pub = (MPKCPublicKey)akp.PublicKey; byte[] enc = pub.ToBytes(); using (MPKCPublicKey pub2 = MPKCPublicKey.From(enc)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } if (pub.GetHashCode() != pub2.GetHashCode()) { throw new Exception("EncryptionKey: public key hash test failed!"); } } OnProgress(new TestEventArgs("Passed public key serialization")); MemoryStream pubstr = pub.ToStream(); using (MPKCPublicKey pub2 = MPKCPublicKey.From(pubstr)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } if (pub.GetHashCode() != pub2.GetHashCode()) { throw new Exception("EncryptionKey: public key hash test failed!"); } } pubstr.Dispose(); OnProgress(new TestEventArgs("Passed public key stream test")); MPKCPrivateKey pri = (MPKCPrivateKey)akp.PrivateKey; enc = pri.ToBytes(); using (MPKCPrivateKey pri2 = new MPKCPrivateKey(enc)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } if (pri.GetHashCode() != pri2.GetHashCode()) { throw new Exception("EncryptionKey: private key hash test failed!"); } } OnProgress(new TestEventArgs("Passed private key serialization")); MemoryStream pristr = pri.ToStream(); using (MPKCPrivateKey pri2 = MPKCPrivateKey.From(pristr)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } if (pri.GetHashCode() != pri2.GetHashCode()) { throw new Exception("EncryptionKey: private key hash test failed!"); } } pristr.Dispose(); OnProgress(new TestEventArgs("Passed private key stream test")); using (MPKCEncrypt mpe = new MPKCEncrypt(mpar)) { mpe.Initialize(akp.PublicKey); int sz = mpe.MaxPlainText - 1; byte[] data = new byte[sz]; new VTDev.Libraries.CEXEngine.Crypto.Prng.CSPPrng().GetBytes(data); enc = mpe.Encrypt(data); mpe.Initialize(akp.PrivateKey); byte[] dec = mpe.Decrypt(enc); if (!Evaluate.AreEqual(dec, data)) { throw new Exception("EncryptionKey: decryption failure!"); } OnProgress(new TestEventArgs("Passed encryption test")); } pri.Dispose(); pub.Dispose(); }
/// <summary> /// Decrypt an array with an asymmetric cipher /// </summary> private byte[] AsymmetricDecrypt(IAsymmetricParameters Parameters, IAsymmetricKeyPair KeyPair, byte[] Data) { using (IAsymmetricCipher cipher = GetAsymmetricCipher(Parameters)) { if (cipher.GetType().Equals(typeof(NTRUEncrypt))) ((NTRUEncrypt)cipher).Initialize(KeyPair); else cipher.Initialize(KeyPair.PrivateKey); return cipher.Decrypt(Data); } }
private static void TestSign(GMSSParameters CipherParam) { GMSSKeyGenerator mkgen = new GMSSKeyGenerator(CipherParam); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); byte[] data = new byte[200]; new VTDev.Libraries.CEXEngine.Crypto.Prng.CSPPrng().GetBytes(data); // public key serialization test: var pubKeySerialized = akp.PublicKey.ToBytes(); var pubKeyExported = $"-----BEGIN GMSS PUBLIC KEY-----{Environment.NewLine}{Convert.ToBase64String(pubKeySerialized, Base64FormattingOptions.InsertLineBreaks)}{Environment.NewLine}-----END GMSS PUBLIC KEY-----{Environment.NewLine}"; File.WriteAllText("TestPublicKey.txt", pubKeyExported); var pubKeyImported = File.ReadAllText("TestPublicKey.txt").Replace($"-----BEGIN GMSS PUBLIC KEY-----{Environment.NewLine}", "").Replace($"-----END GMSS PUBLIC KEY-----{Environment.NewLine}", ""); var pubKey = GMSSPublicKey.From(Convert.FromBase64String(pubKeyImported)); var currentPrivKey = ((GMSSPrivateKey)akp.PrivateKey); //.NextKey(); for (int i = 0; i < 10; i++) //2000; i++) { try { //var test = JsonConvert.SerializeObject(akp); using (GMSSSign sgn = new GMSSSign(CipherParam)) { //////// sign the array //////sgn.Initialize(akp.PrivateKey); //////byte[] code = sgn.Sign(data, 0, data.Length); //////// verify the signature //////sgn.Initialize(akp.PublicKey); //////if (!sgn.Verify(data, 0, data.Length, code)) ////// throw new Exception("RLWESignTest: Sign operation failed!"); //if (i == 15) try { //var test1 = JsonConvert.SerializeObject(currentPrivKey); //var keyBytes = currentPrivKey.ToBytes(); //var currentPrivKeyCopy = currentPrivKey.DeepCopy(); // private key serialization test //if (i == 19) // currentPrivKey.DebugGetTreehashes("before"); var privKeySerialized = currentPrivKey.ToBytes(); var privKeyExported = $"-----BEGIN GMSS.{GMSSVersion} PRIVATE KEY-----{Environment.NewLine}{Convert.ToBase64String(privKeySerialized, Base64FormattingOptions.InsertLineBreaks)}{Environment.NewLine}-----END GMSS PRIVATE KEY-----{Environment.NewLine}"; File.WriteAllText("TestPrivateKey.txt", privKeyExported); var privKeyImported = File.ReadAllText("TestPrivateKey.txt").Replace($"-----BEGIN GMSS.{GMSSVersion} PRIVATE KEY-----{Environment.NewLine}", "").Replace($"-----END GMSS PRIVATE KEY-----{Environment.NewLine}", ""); var currentPrivKeyRegen = GMSSPrivateKey.From(Convert.FromBase64String(privKeyImported)); //if (i == 19) { using (SHA512Managed sha = new SHA512Managed()) { var test1 = Convert.ToBase64String(sha.ComputeHash(currentPrivKey.ToBytes())); var test2 = Convert.ToBase64String(sha.ComputeHash(currentPrivKeyRegen.ToBytes())); var iAmI = i; if (test1 != test2) { //////GMSSPrivateKey.DEBUG_HIT_NOW = true; var test1b = ByteArrayToString(currentPrivKey.ToBytes()); var test2b = ByteArrayToString(currentPrivKeyRegen.ToBytes()); } else { } } } // currentPrivKey.DebugGetTreehashes("after"); //var xxx = 1; currentPrivKey = currentPrivKeyRegen; //var testXXX = currentPrivKey.NextKey(); //var test2 = JsonConvert.SerializeObject(currentPrivKeyCopy); //var test3 = JsonConvert.SerializeObject(currentPrivKey); //if(test1 != test2 || test2 != test3) //{ //} //currentPrivKey = new GMSSPrivateKey() //var test1 = currentPrivKey.IsUsed; //using (SHA256Managed sha = new SHA256Managed()) //{ // var currentPrivKeyHash = Convert.ToBase64String(sha.ComputeHash(keyBytes)); //} } catch (Exception ex) { throw ex; } //////var test1 = currentPrivKey.ToBytes(); sgn.Initialize(currentPrivKey); var code = sgn.Sign(new MemoryStream(data)); File.WriteAllText("TestSignature.txt", Convert.ToBase64String(code)); // verify the signature sgn.Initialize(pubKey); if (!sgn.Verify(new MemoryStream(data), code)) { throw new Exception("RLWESignTest: Verify test failed!"); } try { // get the next available key (private sub-key is used only once) //////GMSSPrivateKey nk = ((GMSSPrivateKey)akp.PrivateKey).NextKey(); currentPrivKey = currentPrivKey.NextKey(); // ((GMSSPrivateKey)akp.PrivateKey).NextKey(); // currentPrivKey.NextKey(); } catch (Exception ex) { throw ex; } } } catch (Exception ex) { throw ex; } } }
/// <summary> /// Sends the servers Primary-Stage <see cref="IAsymmetricKey">AsymmetricKey</see> Public key. /// </summary> /// /// <returns>A Stream containing the raw packet data</returns> private MemoryStream CreatePrimeEx() { // get the cipher parameters _srvAsmParams = GetAsymmetricParams(_srvIdentity.PkeId); // create new public key pair _primKeyPair = GenerateAsymmetricKeyPair(_srvAsmParams); // serailize the public key byte[] keyBytes = _primKeyPair.PublicKey.ToBytes(); // pad public key keyBytes = WrapMessage(keyBytes, _dtmParameters.MaxAsmKeyAppend, _dtmParameters.MaxAsmKeyPrePend); // encrypt the servers public key byte[] enc = SymmetricTransform(_srvSymProcessor, keyBytes); // payload container MemoryStream pldStm = new MemoryStream(enc); // stage completed _exchangeState = DtmExchangeFlags.PrimeEx; // optional wait random timeout if (_dtmParameters.MaxAsmKeyDelayMS > 0) SendWait(_dtmParameters.MaxAsmKeyDelayMS, _dtmParameters.MaxAsmKeyDelayMS / 2); return pldStm; }
public BaseMethods() { encParams = (MPKCParameters)MPKCParamSets.MPKCFM11T40S256.DeepCopy(); keyGen = new MPKCKeyGenerator(encParams); keyPair = keyGen.GenerateKeyPair(); }
/// <summary> /// Tear down the connection; destroys all structures provided by this class /// </summary> private void TearDown() { if (_rndGenerator != null) { _rndGenerator.Dispose(); _rndGenerator = null; } if (_authKeyPair != null) { _authKeyPair.Dispose(); _authKeyPair = null; } if (_cltAsmParams != null) { _cltAsmParams.Dispose(); _cltAsmParams = null; } if (_cltPublicKey != null) { _cltPublicKey.Dispose(); _cltPublicKey = null; } if (_primKeyPair != null) { _primKeyPair.Dispose(); _primKeyPair = null; } // cipher streaming managed through class if (SessionEstablished == null || _disposeEngines == true) { if (_cltKeyParams != null) { _cltKeyParams.Dispose(); _cltKeyParams = null; } if (_srvKeyParams != null) { _srvKeyParams.Dispose(); _srvKeyParams = null; } if (_srvSymProcessor != null) { _srvSymProcessor.Dispose(); _srvSymProcessor = null; } if (_cltSymProcessor != null) { _cltSymProcessor.Dispose(); _cltSymProcessor = null; } } _bufferCount = 0; _bytesSent = 0; _bytesReceived = 0; _cltIdentity.Reset(); _fileCounter = 0; _maxSendCounter = 0; _maxSendAttempts = MAXSNDATTEMPT; _rcvSequence = 0; _sndSequence = 0; }
private void TestEncode() { RNBWParameters mpar = RNBWParamSets.FromName(RNBWParamSets.RNBWParamNames.N33L5); RNBWKeyGenerator mkgen = new RNBWKeyGenerator(mpar); IAsymmetricKeyPair akp = mkgen.GenerateKeyPair(); RNBWPublicKey pub = (RNBWPublicKey)akp.PublicKey; byte[] enc = pub.ToBytes(); using (RNBWPublicKey pub2 = RNBWPublicKey.From(enc)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } if (pub.GetHashCode() != pub2.GetHashCode()) { throw new Exception("EncryptionKey: public key hash test failed!"); } } OnProgress(new TestEventArgs("Passed public key serialization")); MemoryStream pubstr = pub.ToStream(); using (RNBWPublicKey pub2 = RNBWPublicKey.From(pubstr)) { if (!pub.Equals(pub2)) { throw new Exception("EncryptionKey: public key comparison test failed!"); } if (pub.GetHashCode() != pub2.GetHashCode()) { throw new Exception("EncryptionKey: public key hash test failed!"); } } pubstr.Dispose(); OnProgress(new TestEventArgs("Passed public key stream test")); RNBWPrivateKey pri = (RNBWPrivateKey)akp.PrivateKey; enc = pri.ToBytes(); using (RNBWPrivateKey pri2 = RNBWPrivateKey.From(enc)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } if (pri.GetHashCode() != pri2.GetHashCode()) { throw new Exception("EncryptionKey: private key hash test failed!"); } } OnProgress(new TestEventArgs("Passed private key serialization")); MemoryStream pristr = pri.ToStream(); using (RNBWPrivateKey pri2 = RNBWPrivateKey.From(pristr)) { if (!pri.Equals(pri2)) { throw new Exception("EncryptionKey: private key comparison test failed!"); } if (pri.GetHashCode() != pri2.GetHashCode()) { throw new Exception("EncryptionKey: private key hash test failed!"); } } pristr.Dispose(); OnProgress(new TestEventArgs("Passed private key stream test")); pri.Dispose(); pub.Dispose(); }