Exemplo n.º 1
0
        public void TestExtractDestination()
        {
            var keyDestinations = new []
            {
                new[]
                {
                    "TefXQofupTzTYIVE4YQ5M39hmfPiQTzpIKezWlqE5-Td0xF-dR6ck~zOsZwKGm5me3MCoirZGYgHRBYbpvGfdg8wzx4MNrARBMivjlI6JHb694cqA53dFpBaoIwvPxOpXT08rJPY84UCVKKl-OYcqQBFiR9nKiXwfjmPGx22lxo6Okg1Tihpaz8amA4GBi2WH-2mGZj~iAOsl81Ll~G~tBGJHxR57KSIKPU8FuglmOUarrYJBh6YYX0EcAyEmaLyGiULhAVhczg9vucDuPyU5-Vfw3rVciAteMUuU9VVmQA8kEyxqcmqPwAKQStCApw9jEX4vVJXWJ5cbknt4J3~fE3POYk9kG9b-Xhuo6jJDe7oEYVsCLW34nopMlWydLONgetlRUiW4-LdSg9MEuupY4AZYzTSXRxZ7hlmWO6xmbmBAr6F7oQQxd8dcWaOYH~zrCbvrhEYaWAVmegd0s~Yv4Yb~GoJXHst~wdLzH3Jz-lXC4O5bEW5tJezP~Q8HJUCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACL5w0IK~bao-xKw9RCS9EV~LP-lv9iQSgymJmDFCOQAeuCj20W2vltzfUA4PChCFD",
                    "TefXQofupTzTYIVE4YQ5M39hmfPiQTzpIKezWlqE5-Td0xF-dR6ck~zOsZwKGm5me3MCoirZGYgHRBYbpvGfdg8wzx4MNrARBMivjlI6JHb694cqA53dFpBaoIwvPxOpXT08rJPY84UCVKKl-OYcqQBFiR9nKiXwfjmPGx22lxo6Okg1Tihpaz8amA4GBi2WH-2mGZj~iAOsl81Ll~G~tBGJHxR57KSIKPU8FuglmOUarrYJBh6YYX0EcAyEmaLyGiULhAVhczg9vucDuPyU5-Vfw3rVciAteMUuU9VVmQA8kEyxqcmqPwAKQStCApw9jEX4vVJXWJ5cbknt4J3~fE3POYk9kG9b-Xhuo6jJDe7oEYVsCLW34nopMlWydLONgetlRUiW4-LdSg9MEuupY4AZYzTSXRxZ7hlmWO6xmbmBAr6F7oQQxd8dcWaOYH~zrCbvrhEYaWAVmegd0s~Yv4Yb~GoJXHst~wdLzH3Jz-lXC4O5bEW5tJezP~Q8HJUCAAAA"
                },
                new []
                {
                    "NK4USq1-mR1oK-J9~htlNTXgB5bjLS8i8aKXz~M14pwRp0qOryrXU9c6Pqip7VbJntjAtfNCFu6-SegpNIVWMcwNL-GyrxQPij9s8cYU8ra6wPZV~-pLnFui-7xG~t9A8wBAUEj94joGVCLMedQ7yP0BUaJn9lfvPALvgJxiioa-m-OaOPMtUTFke77ZL0GBDxRm-z9KMEuJWRBWZOJmbKZOpexllw~N7W68r2wapiaqx4eYIskyRwH9SdIaV9q8OOfKIRFzmyJ5-47er57K7UlCGtxtdXbrnoVybpp-5mYcYfolqzA~IEPMo7TOFxEpBNdSXKFfhWm70PTt4GQedS~njJZj4Z2aCRk4uSOTRF6pYwuK5-kncHr4jCGivCTgjVt1LQaKmfNKLLMmJsmkuE9Szb8DU4rbt4H3pMJcP3wssNleXiBUawfN642mgechWshwnO09D0SRgcV480rh3YrIt-my1CXCzB6ay2ZwW6OFhDvGjuLAL4s-fTT~XOzlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGqPkndWfsxSWhKOtHywH9KPdJyysKmD9YwIn5AOLgIoWKoUpiF1HwEoMAH-XesLD",
                    "NK4USq1-mR1oK-J9~htlNTXgB5bjLS8i8aKXz~M14pwRp0qOryrXU9c6Pqip7VbJntjAtfNCFu6-SegpNIVWMcwNL-GyrxQPij9s8cYU8ra6wPZV~-pLnFui-7xG~t9A8wBAUEj94joGVCLMedQ7yP0BUaJn9lfvPALvgJxiioa-m-OaOPMtUTFke77ZL0GBDxRm-z9KMEuJWRBWZOJmbKZOpexllw~N7W68r2wapiaqx4eYIskyRwH9SdIaV9q8OOfKIRFzmyJ5-47er57K7UlCGtxtdXbrnoVybpp-5mYcYfolqzA~IEPMo7TOFxEpBNdSXKFfhWm70PTt4GQedS~njJZj4Z2aCRk4uSOTRF6pYwuK5-kncHr4jCGivCTgjVt1LQaKmfNKLLMmJsmkuE9Szb8DU4rbt4H3pMJcP3wssNleXiBUawfN642mgechWshwnO09D0SRgcV480rh3YrIt-my1CXCzB6ay2ZwW6OFhDvGjuLAL4s-fTT~XOzlAAAA"
                }
            };

            foreach (var pair in keyDestinations)
            {
                var privateKeyString  = pair[0];
                var privateKey        = new I2PPrivateKey(privateKeyString);
                var destinationString = privateKey.Destination.ToI2PBase64();
                Assert.Equal(destinationString, pair[1]);
                Assert.Equal(privateKey.ToI2PBase64(), privateKeyString);
                _output.WriteLine("#####" + destinationString);
            }
        }
Exemplo n.º 2
0
        internal static byte[] Send(DHHandshakeContext context)
        {
            var dest   = new byte[288];
            var writer = new BufRefLen(dest);

            var keys = I2PPrivateKey.GetNewKeyPair();

            context.PrivateKey = keys.PrivateKey;
            context.X          = keys.PublicKey;
            context.XBuf       = context.X.Key;

            context.HXxorHI = new BufLen(I2PHashSHA256.GetHash(context.XBuf));

            Logging.LogDebugData(
                $"SessionRequest: Remote cert: {context.RemoteRI.Certificate}. XBuf len: {context.XBuf.Length}");

            var idenhash = context.RemoteRI.IdentHash;

            for (int i = 0; i < context.HXxorHI.Length; ++i)
            {
                context.HXxorHI[i] ^= idenhash.Hash[i];
            }

            writer.Write(context.XBuf);
            writer.Write(context.HXxorHI);

            return(dest);
        }
Exemplo n.º 3
0
        internal static byte[] Send(DHHandshakeContext context)
        {
            var dest   = new byte[288];
            var writer = new BufRefLen(dest);

            var keys = I2PPrivateKey.GetNewKeyPair();

            context.PrivateKey = keys.PrivateKey;
            context.X          = keys.PublicKey;
            context.XBuf       = context.X.Key;

            context.HXxorHI = new BufLen(I2PHashSHA256.GetHash(context.XBuf));

#if LOG_ALL_TRANSPORT
            Logging.LogTransport(
                "SessionRequest: Remote cert: " + context.RemoteRI.Certificate.ToString() + ". XBuf len: " + context.XBuf.Length.ToString());
#endif
            var idenhash = context.RemoteRI.IdentHash;
            for (int i = 0; i < context.HXxorHI.Length; ++i)
            {
                context.HXxorHI[i] ^= idenhash.Hash[i];
            }

            writer.Write(context.XBuf);
            writer.Write(context.HXxorHI);

            return(dest);
        }
Exemplo n.º 4
0
        public static (GarlicAESBlock, I2PSessionKey) EGDecryptGarlic(
            GarlicMessage garlic,
            I2PPrivateKey privkey)
        {
            var cipher = new CbcBlockCipher(new AesEngine());
            var egdata = garlic.EGData;

            var egbuf    = new BufLen(egdata, 0, 514);
            var egheader = ElGamalCrypto.Decrypt(egbuf, privkey, true);

            var sessionkey = new I2PSessionKey(new BufLen(egheader, 0, 32));
            var preiv      = new BufLen(egheader, 32, 32);
            var egpadding  = new BufLen(egheader, 64, 158);
            var aesbuf     = new BufLen(egdata, 514);

            var pivh = I2PHashSHA256.GetHash(preiv);

            cipher.Init(false, sessionkey.Key.ToParametersWithIV(new BufLen(pivh, 0, 16)));
            cipher.ProcessBytes(aesbuf);

            GarlicAESBlock aesblock =
                new GarlicAESBlock(new BufRefLen(aesbuf));

            if (!aesblock.VerifyPayloadHash())
            {
                throw new ChecksumFailureException("AES block hash check failed!");
            }

            return(aesblock, sessionkey);
        }
Exemplo n.º 5
0
        private void Load(string filename)
        {
            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (var ms = new MemoryStream())
                {
                    byte[] buf = new byte[8192];
                    int    len;
                    while ((len = fs.Read(buf, 0, buf.Length)) != 0)
                    {
                        ms.Write(buf, 0, len);
                    }

                    var reader = new BufRefLen(ms.ToArray());

                    Certificate       = new I2PCertificate(reader);
                    PrivateSigningKey = new I2PSigningPrivateKey(reader, Certificate);
                    PublicSigningKey  = new I2PSigningPublicKey(reader, Certificate);

                    PrivateKey = new I2PPrivateKey(reader, Certificate);
                    PublicKey  = new I2PPublicKey(reader, Certificate);

                    MyRouterIdentity = new I2PRouterIdentity(reader);
                    Published        = new I2PDate(reader);
                    IntroKey         = reader.ReadBufLen(32);
                }
            }
        }
Exemplo n.º 6
0
        public SessionRequestState(SSUSession sess) : base(sess)
        {
            var keys = I2PPrivateKey.GetNewKeyPair();

            PrivateKey = keys.PrivateKey;
            X          = keys.PublicKey;
        }
Exemplo n.º 7
0
        public ElGamalTest()
        {
            Private = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            Public  = new I2PPublicKey(Private);

            Me = new I2PRouterIdentity(Public, new I2PSigningPublicKey(new BigInteger("12"), I2PKeyType.DefaultSigningKeyCert));
        }
Exemplo n.º 8
0
        public SessionCreatedState(SSUSession sess)
            : base(sess)
        {
            var keys = I2PPrivateKey.GetNewKeyPair();

            PrivateKey = keys.PrivateKey;
            Y          = keys.PublicKey;
        }
Exemplo n.º 9
0
        public SessionRequestState(SSUSession sess, bool remoteisfirewalled) : base(sess)
        {
            RemoteIsFirewalled = remoteisfirewalled;

            var keys = I2PPrivateKey.GetNewKeyPair();

            PrivateKey = keys.PrivateKey;
            X          = keys.PublicKey;
        }
Exemplo n.º 10
0
        public SessionCreatedState(SSUSession sess)
            : base(sess)
        {
            var keys = I2PPrivateKey.GetNewKeyPair();

            PrivateKey = keys.PrivateKey;
            Y          = keys.PublicKey;

            Session.MACKey    = Session.MyRouterContext.IntroKey;
            Session.SharedKey = Session.MyRouterContext.IntroKey;
        }
Exemplo n.º 11
0
        public CreateLeaseSetMessage(BufRef reader, I2CPSession session)
            : base(ProtocolMessageType.CreateLS)
        {
            SessionId = reader.ReadFlip16();

            var cert = session.SessionIds[SessionId].Config.Destination.Certificate;

            DSAPrivateSigningKey = new I2PSigningPrivateKey(
                reader,
                new I2PCertificate(I2PSigningKey.SigningKeyTypes.DSA_SHA1));

            PrivateKey = new I2PPrivateKey(reader, cert);
            Leases     = new I2PLeaseSet(reader);
        }
Exemplo n.º 12
0
        public I2NPMessagesTest()
        {
            Private        = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            Public         = new I2PPublicKey(Private);
            PrivateSigning = new I2PSigningPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            PublicSigning  = new I2PSigningPublicKey(PrivateSigning);

            var CertificateEd25519 = new I2PCertificate(I2PSigningKey.SigningKeyTypes.EdDSA_SHA512_Ed25519);

            PrivateSigningEd25519 = new I2PSigningPrivateKey(CertificateEd25519);
            PublicSigningEd25519  = new I2PSigningPublicKey(PrivateSigningEd25519);

            Me = new I2PRouterIdentity(Public, new I2PSigningPublicKey(new BigInteger("12"), I2PKeyType.DefaultSigningKeyCert));
        }
Exemplo n.º 13
0
        public GarlicTest()
        {
            Private = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            Public  = new I2PPublicKey(Private);

            Me = new I2PRouterIdentity(Public, new I2PSigningPublicKey(new BigInteger("12"), I2PKeyType.DefaultSigningKeyCert));

            DestinationPrivate = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            DestinationPublic  = new I2PPublicKey(DestinationPrivate);
            Destination        = new I2PRouterIdentity(DestinationPublic, new I2PSigningPublicKey(new BigInteger("277626"), I2PKeyType.DefaultSigningKeyCert));

            PrivateSigning = new I2PSigningPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            PublicSigning  = new I2PSigningPublicKey(PrivateSigning);
        }
Exemplo n.º 14
0
        public void TestReadWriteI2PLong()
        {
            byte[] b1 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
            _output.WriteLine(BitConverter.ToString(b1));
            long  i1;
            int   i2;
            short i3;
            sbyte i4;

            using (var ms = new MemoryStream(b1))
            {
                i1 = I2PPrivateKey.ReadLong(ms, 8);
            }
            using (var ms = new MemoryStream(b1))
            {
                i2 = (int)I2PPrivateKey.ReadLong(ms, 4);
            }
            using (var ms = new MemoryStream(b1))
            {
                i3 = (short)I2PPrivateKey.ReadLong(ms, 2);
            }
            using (var ms = new MemoryStream(b1))
            {
                i4 = (sbyte)I2PPrivateKey.ReadLong(ms, 1);
            }
            _output.WriteLine("{0} {1} {2} {3}", i1, i2, i3, i4);
            using (var ms = new MemoryStream())
            {
                I2PPrivateKey.WriteLong(ms, 8, i1);
                _output.WriteLine(BitConverter.ToString(ms.ToArray()));
            }
            using (var ms = new MemoryStream())
            {
                I2PPrivateKey.WriteLong(ms, 4, i2);
                _output.WriteLine(BitConverter.ToString(ms.ToArray()));
            }
            using (var ms = new MemoryStream())
            {
                I2PPrivateKey.WriteLong(ms, 2, i3);
                _output.WriteLine(BitConverter.ToString(ms.ToArray()));
            }
            using (var ms = new MemoryStream())
            {
                I2PPrivateKey.WriteLong(ms, 1, i4);
                _output.WriteLine(BitConverter.ToString(ms.ToArray()));
            }
        }
Exemplo n.º 15
0
        public GarlicTest()
        {
            Logging.LogToConsole = true;
            Logging.LogLevel     = Logging.LogLevels.DebugData;

            Private = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            Public  = new I2PPublicKey(Private);

            Me = new I2PRouterIdentity(Public, new I2PSigningPublicKey(new BigInteger("12"), I2PKeyType.DefaultSigningKeyCert));

            DestinationPrivate = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            DestinationPublic  = new I2PPublicKey(DestinationPrivate);
            Destination        = new I2PRouterIdentity(DestinationPublic, new I2PSigningPublicKey(new BigInteger("277626"), I2PKeyType.DefaultSigningKeyCert));

            PrivateSigning = new I2PSigningPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
            PublicSigning  = new I2PSigningPublicKey(PrivateSigning);
        }
Exemplo n.º 16
0
        public void TestI2PDestination()
        {
            var certificate = new I2PCertificate(I2PSigningKey.SigningKeyTypes.EdDSA_SHA512_Ed25519);

            var keys = I2PPrivateKey.GetNewKeyPair();

            var privkey  = keys.PrivateKey;
            var privskey = new I2PSigningPrivateKey(certificate);

            var dest = new I2PDestination(
                keys.PublicKey,
                new I2PSigningPublicKey(privskey));

            var d2 = new I2PDestination(new BufRefLen(dest.ToByteArray()));

            Assert.IsTrue(BufUtils.Equal(dest.ToByteArray(), d2.ToByteArray()));
        }
Exemplo n.º 17
0
        public TunnelBuildRequestDecrypt(
            IEnumerable <AesEGBuildRequestRecord> records,
            I2PIdentHash me,
            I2PPrivateKey key)
        {
            RecordsField = records;
            Me           = me;
            Key          = key;

            ToMeField = RecordsField.FirstOrDefault(rec => Me.Hash16 == rec.ToPeer16);

            if (ToMeField != null)
            {
                MyRecord        = new EGBuildRequestRecord(ToMeField);
                DecryptedRecord = MyRecord.Decrypt(key);
            }
        }
Exemplo n.º 18
0
        public static ClientDestination CreateDestination(I2PDestination dest, I2PPrivateKey privkey, bool publish, out bool alreadyrunning)
        {
            lock ( RunningDestinations )
            {
                if (RunningDestinations.TryGetValue(dest, out var runninginst))
                {
                    alreadyrunning = true;
                    return(runninginst);
                }

                var newclient = new ClientDestination(dest, privkey, publish);
                RunningDestinations[dest] = newclient;
                ClientMgr.AttachClient(newclient);
                alreadyrunning = false;
                return(newclient);
            }
        }
Exemplo n.º 19
0
        private void NewIdentity(I2PCertificate cert)
        {
            Published   = new I2PDate(DateTime.UtcNow.AddMinutes(-1));
            Certificate = cert != null ? cert : new I2PCertificate(I2PSigningKey.SigningKeyTypes.EdDSA_SHA512_Ed25519);
            //Certificate = new I2PCertificate( I2PSigningKey.SigningKeyTypes.EdDSA_SHA512_Ed25519 );
            //Certificate = new I2PCertificate( I2PSigningKey.SigningKeyTypes.ECDSA_SHA256_P256 );
            //Certificate = new I2PCertificate( I2PSigningKey.SigningKeyTypes.ECDSA_SHA384_P384 );
            //Certificate = new I2PCertificate( I2PSigningKey.SigningKeyTypes.DSA_SHA1 );
            PrivateSigningKey = new I2PSigningPrivateKey(Certificate);
            PublicSigningKey  = new I2PSigningPublicKey(PrivateSigningKey);

            var keys = I2PPrivateKey.GetNewKeyPair();

            PrivateKey = keys.PrivateKey;
            PublicKey  = keys.PublicKey;

            MyRouterIdentity = new I2PRouterIdentity(PublicKey, PublicSigningKey);
            IntroKey.Randomize();
        }
Exemplo n.º 20
0
        public static BufLen Decrypt(BufLen data, I2PPrivateKey pkey, bool zeropad)
        {
            if (data == null || (zeropad && data.Length != 514))
            {
                throw new ArgumentException("ElGamal padded data to decrypt must be exactly 514 bytes!");
            }
            if (!zeropad && data.Length != 512)
            {
                throw new ArgumentException("ElGamal data to decrypt must be exactly 512 bytes!");
            }

            var x = I2PConstants.ElGamalP.Subtract(pkey.ToBigInteger()).Subtract(BigInteger.One);

            BigInteger a, b;
            var        reader = new BufRefLen(data);

            if (zeropad)
            {
                reader.Seek(1);
                a = reader.ReadBigInteger(256);
                reader.Seek(1);
                b = reader.ReadBigInteger(256);
            }
            else
            {
                a = reader.ReadBigInteger(256);
                b = reader.ReadBigInteger(256);
            }

            var m2   = b.Multiply(a.ModPow(x, I2PConstants.ElGamalP));
            var m1   = m2.Mod(I2PConstants.ElGamalP);
            var m    = m1.ToByteArray(255);
            var hash = I2PHashSHA256.GetHash(m, 33, 222);

            if (!BufUtils.Equal(m, 1, hash, 0, 32))
            {
                throw new HashCheckFailException();
            }

            return(new BufLen(m, 33, 222));
        }
Exemplo n.º 21
0
        public void TestEGCompatibilityDecode()
        {
            var priv = new I2PPrivateKey(
                new BufRefLen(FreenetBase64.Decode(PRIVATE_KEY)),
                new I2PCertificate());

            var pub = new I2PPublicKey(
                new BufRefLen(FreenetBase64.Decode(PUBLIC_KEY)),
                new I2PCertificate());

            for (int i = 0; i < ENCRYPTED.Length; ++i)
            {
                var decr = ElGamalCrypto.Decrypt(
                    new BufLen(FreenetBase64.Decode(ENCRYPTED[i])),
                    priv,
                    true);

                var clear = new BufLen(Encoding.UTF8.GetBytes(UNENCRYPTED[i]));
                Assert.IsTrue(decr == clear);
            }
        }
Exemplo n.º 22
0
        internal static byte[] Send(DHHandshakeContext context)
        {
            var clear  = new byte[304];
            var writer = new BufRefLen(clear);

            var keys = I2PPrivateKey.GetNewKeyPair();

            context.PrivateKey = keys.PrivateKey;
            context.Y          = keys.PublicKey;
            context.YBuf       = new BufLen(context.Y.Key);

            var sharedkey = BufUtils.DHI2PToByteArray(context.X.ToBigInteger().ModPow(context.PrivateKey.ToBigInteger(), I2PConstants.ElGamalP));

            context.SessionKey = new I2PSessionKey(sharedkey);

            writer.Write(context.YBuf);

            context.TimestampB = (uint)(DateTime.UtcNow - I2PDate.RefDate).TotalSeconds;

            writer.Write(I2PHashSHA256.GetHash(context.XBuf, context.YBuf));
            writer.WriteFlip32(context.TimestampB);
            writer.Write(BufUtils.Random(12));

            var key = new KeyParameter(context.SessionKey.Key.ToByteArray());

            var iv = context.YBuf.PeekB(context.YBuf.Length - 16, 16);

            context.Encryptor = new CbcBlockCipher(new AesEngine());
            context.Encryptor.Init(true, new ParametersWithIV(key, iv, 0, 16));

            iv = context.HXxorHI.PeekB(context.HXxorHI.Length - 16, 16);

            context.Dectryptor = new CbcBlockCipher(new AesEngine());
            context.Dectryptor.Init(false, new ParametersWithIV(key, iv, 0, 16));

            context.Encryptor.ProcessBytes(new BufLen(clear, 256, 48));

            return(clear);
        }
Exemplo n.º 23
0
        public static BufLen Decrypt(BufLen data, I2PPrivateKey pkey, bool zeropad)
        {
            if (data == null || zeropad && data.Length != EncryptedPaddedLength)
            {
                throw new ArgumentException($"ElGamal padded data to decrypt must be exactly {EncryptedPaddedLength} bytes!");
            }

            if (!zeropad && data.Length != EncryptedShortLength)
            {
                throw new ArgumentException($"ElGamal data to decrypt must be exactly {EncryptedShortLength} bytes!");
            }

            var x = I2PConstants.ElGamalPMinusOne.Subtract(pkey.ToBigInteger());

            var reader = new BufRefLen(data);

            var readlen = zeropad
                        ? EncryptedPaddedLength / 2
                        : EncryptedShortLength / 2;

            var a = reader.ReadBigInteger(readlen);
            var b = reader.ReadBigInteger(readlen);

            var m2      = b.Multiply(a.ModPow(x, I2PConstants.ElGamalP));
            var m1      = m2.Mod(I2PConstants.ElGamalP);
            var m       = m1.ToByteArrayUnsigned();
            var payload = new BufLen(m, 33, ClearTextLength);
            var hash    = I2PHashSHA256.GetHash(payload);

            if (!BufUtils.Equal(m, 1, hash, 0, 32))
            {
                throw new HashCheckFailException();
            }

            return(payload);
        }
Exemplo n.º 24
0
 public BuildRequestRecord Decrypt(I2PPrivateKey pkey)
 {
     return(new BuildRequestRecord(new BufRef(ElGamalCrypto.Decrypt(EncryptedData, pkey, false))));
 }
Exemplo n.º 25
0
 public DecryptReceivedSessions(object owner, I2PPrivateKey key)
 {
     Owner      = owner;
     PrivateKey = key;
 }
Exemplo n.º 26
0
 public ElGamalTest()
 {
     Private = new I2PPrivateKey(I2PKeyType.DefaultAsymetricKeyCert);
     Public  = new I2PPublicKey(Private);
 }
Exemplo n.º 27
0
 public ReceivedSessions(I2PPrivateKey key)
 {
     Key = key;
 }
Exemplo n.º 28
0
        public static (GarlicAESBlock, I2PSessionKey) RetrieveAESBlock(
            GarlicMessage garlic,
            I2PPrivateKey privatekey,
            Func <I2PSessionTag, I2PSessionKey> findsessionkey)
        {
            GarlicAESBlock result;

            var cipher = new CbcBlockCipher(new AesEngine());

            var tag        = new I2PSessionTag(new BufRefLen(garlic.EGData, 0, 32));
            var sessionkey = findsessionkey?.Invoke(tag);

#if LOG_ALL_LEASE_MGMT
            Logging.LogDebug($"Garlic: Session key found {sessionkey}");
#endif
            if (sessionkey != null)
            {
                var aesbuf = new BufLen(garlic.EGData, 32);
                var pivh   = I2PHashSHA256.GetHash(tag.Value);

                cipher.Init(false, sessionkey.Key.ToParametersWithIV(new BufLen(pivh, 0, 16)));
                cipher.ProcessBytes(aesbuf);

                try
                {
                    result = new GarlicAESBlock(new BufRefLen(aesbuf));

                    if (!result.VerifyPayloadHash())
                    {
                        Logging.LogDebug("Garlic: DecryptMessage: AES block SHA256 check failed.");
                        return(null, null);
                    }

                    return(result, sessionkey);
                }
                catch (ArgumentException ex)
                {
                    Logging.Log("Garlic", ex);
                }
                catch (Exception ex)
                {
                    Logging.Log("Garlic", ex);
                    return(null, null);
                }
            }

#if LOG_ALL_LEASE_MGMT
            Logging.LogDebug("Garlic: No session key. Using ElGamal to decrypt.");
#endif

            try
            {
                (result, sessionkey) = Garlic.EGDecryptGarlic(garlic, privatekey);
#if LOG_ALL_LEASE_MGMT
                Logging.LogDebug($"Garlic: EG session key {sessionkey}");
#endif
            }
            catch (Exception ex)
            {
                Logging.LogDebug("Garlic: ElGamal DecryptMessage failed");
                Logging.LogDebugData($"ReceivedSessions {ex}");
                return(null, null);
            }

            return(result, sessionkey);
        }