Example #1
0
        private static bool EncodeValueString(string s, Encoding?valueEncoding, Span <byte> buffer, out int length)
        {
            if (buffer.Length != 0)
            {
                buffer[0] = 0;

                int encodedStringLength = valueEncoding is null || ReferenceEquals(valueEncoding, Encoding.Latin1)
                    ? s.Length
                    : valueEncoding.GetByteCount(s);

                if (IntegerEncoder.Encode(encodedStringLength, 7, buffer, out int nameLength))
                {
                    buffer = buffer.Slice(nameLength);
                    if (buffer.Length >= encodedStringLength)
                    {
                        if (valueEncoding is null)
                        {
                            EncodeValueStringPart(s, buffer);
                        }
                        else
                        {
                            int written = valueEncoding.GetBytes(s, buffer);
                            Debug.Assert(written == encodedStringLength);
                        }

                        length = nameLength + encodedStringLength;
                        return(true);
                    }
                }
            }

            length = 0;
            return(false);
        }
Example #2
0
        public void CreateTest()
        {
            IntegerEncoder encoder = new IntegerEncoder(GlobalContext.BFVContext);

            Assert.IsNotNull(encoder);
            Assert.AreEqual(65537ul, encoder.PlainModulus.Value);
        }
Example #3
0
        public void ExceptionsTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PlainModulus = new SmallModulus(4ul)
            };
            SEALContext    context      = SEALContext.Create(parms);
            SEALContext    context_null = null;
            IntegerEncoder enc          = new IntegerEncoder(context);
            IntegerEncoder copy_null    = null;
            BigUInt        bui_null     = null;
            BigUInt        bui          = new BigUInt(5ul);
            Plaintext      plain        = new Plaintext();

            Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(context_null));
            Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(copy_null));

            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1ul, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1L, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1u, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null, plain));

            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt32(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt64(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt32(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt64(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeBigUInt(null));
        }
Example #4
0
        public void HPack_IntegerEncode_ShortBuffer(int value, int bits, byte[] expectedResult)
        {
            Span <byte> actualResult = new byte[expectedResult.Length - 1];
            bool        success      = IntegerEncoder.Encode(value, bits, actualResult, out int bytesWritten);

            Assert.False(success);
        }
        /*
         *     0   1   2   3   4   5   6   7
               +---+---+---+---+---+---+---+---+
               |   Required Insert Count (8+)  |
               +---+---------------------------+
               | S |      Delta Base (7+)      |
               +---+---------------------------+
               |      Compressed Headers     ...
               +-------------------------------+
         *
         */
        private static bool EncodeHeaderBlockPrefix(Span<byte> destination, out int bytesWritten)
        {
            int length;
            bytesWritten = 0;
            // Required insert count as first int
            if (!IntegerEncoder.Encode(0, 8, destination, out length))
            {
                return false;
            }

            bytesWritten += length;
            destination = destination.Slice(length);

            // Delta base
            if (destination.IsEmpty)
            {
                return false;
            }

            destination[0] = 0x00;
            if (!IntegerEncoder.Encode(0, 7, destination, out length))
            {
                return false;
            }

            bytesWritten += length;

            return true;
        }
Example #6
0
        public void CreateTest()
        {
            EncryptionParameters parms1 = new EncryptionParameters(SchemeType.BFV)
            {
                PlainModulus = new SmallModulus(8192)
            };
            SEALContext    context1 = SEALContext.Create(parms1);
            IntegerEncoder encoder  = new IntegerEncoder(context1);

            Assert.IsNotNull(encoder);
            Assert.AreEqual(8192ul, encoder.PlainModulus.Value);

            EncryptionParameters parms2 = new EncryptionParameters(SchemeType.BFV)
            {
                PlainModulus = new SmallModulus(4096)
            };
            SEALContext    context2 = SEALContext.Create(parms2);
            IntegerEncoder encoder2 = new IntegerEncoder(context2);

            Assert.IsNotNull(encoder2);
            Assert.AreEqual(4096ul, encoder2.PlainModulus.Value);

            IntegerEncoder encoder3 = new IntegerEncoder(encoder);

            Assert.IsNotNull(encoder3);
            Assert.AreEqual(8192ul, encoder3.PlainModulus.Value);
        }
Example #7
0
        public void DecodeTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PlainModulus = new SmallModulus(1024)
            };
            SEALContext    context = SEALContext.Create(parms);
            IntegerEncoder encoder = new IntegerEncoder(context);

            Plaintext plain = new Plaintext("0x^5 + 1x^4 + 1x^3 + 1x^1 + 0");

            Assert.AreEqual(6ul, plain.CoeffCount);

            ulong resultU64 = encoder.DecodeUInt64(plain);

            Assert.AreEqual(26UL, resultU64);

            long resultI64 = encoder.DecodeInt64(plain);

            Assert.AreEqual(26L, resultI64);

            uint resultU32 = encoder.DecodeUInt32(plain);

            Assert.AreEqual(26U, resultU32);

            int resultI32 = encoder.DecodeInt32(plain);

            Assert.AreEqual(26, resultI32);

            BigUInt bui = encoder.DecodeBigUInt(plain);

            Assert.IsNotNull(bui);
            Assert.AreEqual(0, bui.CompareTo(26ul));
        }
Example #8
0
        public void IntegerEncoderDecoderRoundtrips()
        {
            IntegerDecoder decoder      = new IntegerDecoder();
            Span <byte>    integerBytes = stackalloc byte[5];

            for (int i = 0; i < 2048; ++i)
            {
                for (int prefixLength = 1; prefixLength <= 8; ++prefixLength)
                {
                    integerBytes.Clear();
                    Assert.True(IntegerEncoder.Encode(i, prefixLength, integerBytes, out int length));

                    bool decodeResult = decoder.BeginTryDecode(integerBytes[0], prefixLength, out int intResult);

                    for (int j = 1; j < length; j++)
                    {
                        Assert.False(decodeResult);
                        decodeResult = decoder.TryDecode(integerBytes[j], out intResult);
                    }

                    Assert.True(decodeResult);
                    Assert.Equal(i, intResult);
                }
            }
        }
Example #9
0
        public void ExceptionsTest()
        {
            SEALContext    context      = GlobalContext.BFVContext;
            SEALContext    context_null = null;
            IntegerEncoder enc          = new IntegerEncoder(context);
            BigUInt        bui_null     = null;
            BigUInt        bui          = new BigUInt(5ul);
            Plaintext      plain        = new Plaintext();

            Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(context_null));
            Assert.ThrowsException <ArgumentException>(() => enc     = new IntegerEncoder(GlobalContext.CKKSContext));

            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1ul, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1L, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1u, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui, null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null, plain));

            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt32(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt64(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt32(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt64(null));
            Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeBigUInt(null));
        }
Example #10
0
        public void DecodeTest()
        {
            IntegerEncoder encoder = new IntegerEncoder(GlobalContext.BFVContext);

            Plaintext plain = new Plaintext("0x^5 + 1x^4 + 1x^3 + 1x^1 + 0");

            Assert.AreEqual(6ul, plain.CoeffCount);

            ulong resultU64 = encoder.DecodeUInt64(plain);

            Assert.AreEqual(26UL, resultU64);

            long resultI64 = encoder.DecodeInt64(plain);

            Assert.AreEqual(26L, resultI64);

            uint resultU32 = encoder.DecodeUInt32(plain);

            Assert.AreEqual(26U, resultU32);

            int resultI32 = encoder.DecodeInt32(plain);

            Assert.AreEqual(26, resultI32);

            BigUInt bui = encoder.DecodeBigUInt(plain);

            Assert.IsNotNull(bui);
            Assert.AreEqual(0, bui.CompareTo(26ul));
        }
Example #11
0
        public void IntegerEncoderDecoderRoundtrips()
        {
            var decoder = new IntegerDecoder();
            var range   = 1 << 8;

            foreach (var i in Enumerable.Range(0, range).Concat(Enumerable.Range(int.MaxValue - range + 1, range)))
            {
                for (int n = 1; n <= 8; n++)
                {
                    var integerBytes = new byte[6];
                    Assert.True(IntegerEncoder.Encode(i, n, integerBytes, out var length));

                    var decodeResult = decoder.BeginTryDecode(integerBytes[0], n, out var intResult);

                    for (int j = 1; j < length; j++)
                    {
                        Assert.False(decodeResult);
                        decodeResult = decoder.TryDecode(integerBytes[j], out intResult);
                    }

                    Assert.True(decodeResult);
                    Assert.Equal(i, intResult);
                }
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            int   votersCount = 10000;
            ulong keysize     = 2048;

            int[] votes = createSampleVotes(votersCount, 1);
#if (TEST)
            Console.WriteLine("votes=[{0}]", string.Join(", ", votes));
#endif
            Console.WriteLine("Sum of all votes = {0}", votes.Sum());

            SEALContext    context = createContext(keysize);
            IntegerEncoder encoder = new IntegerEncoder(context);
            KeyGenerator   keygen  = new KeyGenerator(context);

            PublicKey publicKey = keygen.PublicKey;
            SecretKey secretKey = keygen.SecretKey;

            Encryptor encryptor = new Encryptor(context, publicKey);
            Evaluator evaluator = new Evaluator(context);
            Decryptor decryptor = new Decryptor(context, secretKey);

            Ciphertext encryptedTotal = new Ciphertext();
            encryptor.Encrypt(encoder.Encode(0), encryptedTotal);

            Ciphertext encrypted = new Ciphertext();
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Encoding the vote values ... ");



            Stopwatch sw = new Stopwatch();

            sw.Start();
            for (int i = 0; i < votes.Length; i++)
            {
                Plaintext plain = encoder.Encode(votes[i]);
                encryptor.Encrypt(plain, encrypted);
#if (TEST)
                Console.WriteLine($"Noise budget in encrypted: {decryptor.InvariantNoiseBudget(encrypted)} bits");

                Console.WriteLine($"Encoded {votes[i]} as polynomial {plain.ToString()}");
#endif
                evaluator.AddInplace(encryptedTotal, encrypted);
            }
            sw.Stop();
            Console.WriteLine("Elapsed={0}", sw.Elapsed);
            Console.WriteLine("Done");

            Console.WriteLine("-----------------------------------");
            Plaintext plainResult = new Plaintext();
            decryptor.Decrypt(encryptedTotal, plainResult);
            Console.Write($"Decrypting the result polynomial {plainResult.ToString()} ... ");
            Console.WriteLine("Done");

            Console.WriteLine("-----------------------------------");
            Console.WriteLine($"Decoded result: {encoder.DecodeInt32(plainResult)}");
            Console.ReadLine();
        }
Example #13
0
        public void IntegerEncode(int i, int prefixLength, byte[] expectedOctets)
        {
            var buffer = new byte[expectedOctets.Length];

            Assert.True(IntegerEncoder.Encode(i, prefixLength, buffer, out var octets));
            Assert.Equal(expectedOctets.Length, octets);
            Assert.Equal(expectedOctets, buffer);
        }
Example #14
0
 public BfvDecryptor(SEALContext Context, SecretKey PrivateKey)
 {
     //Takes in The original seal context as an argument.
     context = Context;
     //-----------------------------------------------------------------
     //Create an instance of Decryptor with the Generated Private Key.
     decryptor = new Decryptor(context, PrivateKey);
     encoder   = new IntegerEncoder(context);
 }
Example #15
0
        public void HPack_IntegerEncode(int value, int bits, byte[] expectedResult)
        {
            Span <byte> actualResult = new byte[64];
            bool        success      = IntegerEncoder.Encode(value, bits, actualResult, out int bytesWritten);

            Assert.True(success);
            Assert.Equal(expectedResult.Length, bytesWritten);
            Assert.True(actualResult.Slice(0, bytesWritten).SequenceEqual(expectedResult));
        }
        /// <summary>
        /// Encodes just the name part of a Literal Header Field With Static Name Reference. Must call <see cref="EncodeValueString(string, Span{byte}, out int)"/> after to encode the header's value.
        /// </summary>
        public static byte[] EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(int index)
        {
            Span<byte> temp = stackalloc byte[IntegerEncoder.MaxInt32EncodedLength];

            temp[0] = 0b01110000;
            bool res = IntegerEncoder.Encode(index, 4, temp, out int headerBytesWritten);
            Debug.Assert(res == true);

            return temp.Slice(0, headerBytesWritten).ToArray();
        }
Example #17
0
        public static bool EncodeStringLiterals(string[] values, string separator, Span <byte> destination, out int bytesWritten)
        {
            bytesWritten = 0;

            if (values.Length == 0)
            {
                return(EncodeStringLiteral("", destination, out bytesWritten));
            }
            else if (values.Length == 1)
            {
                return(EncodeStringLiteral(values[0], destination, out bytesWritten));
            }

            if (!destination.IsEmpty)
            {
                int valueLength = 0;

                // Calculate length of all parts and separators.
                foreach (string part in values)
                {
                    valueLength = checked ((int)(valueLength + part.Length));
                }

                valueLength = checked ((int)(valueLength + (values.Length - 1) * separator.Length));

                if (IntegerEncoder.Encode(valueLength, 7, destination, out int integerLength))
                {
                    Debug.Assert(integerLength >= 1);

                    int encodedLength = 0;
                    for (int j = 0; j < values.Length; j++)
                    {
                        if (j != 0 && !EncodeStringLiteralValue(separator, destination.Slice(integerLength), out encodedLength))
                        {
                            return(false);
                        }

                        integerLength += encodedLength;

                        if (!EncodeStringLiteralValue(values[j], destination.Slice(integerLength), out encodedLength))
                        {
                            return(false);
                        }

                        integerLength += encodedLength;
                    }

                    bytesWritten = integerLength;
                    return(true);
                }
            }

            return(false);
        }
Example #18
0
        public void generateKeys(int x, int y, string publicFile, string secretFile, string encryptedXFile, string encryptedYFile)
        {
            //Console.WriteLine("Rider at ({0},{1})",x,y);

            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 4096;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);
            parms.PlainModulus      = new Modulus(1024);


            using SEALContext context = new SEALContext(parms);
            //Console.WriteLine("Set encryption parameters and print");
            //Console.WriteLine(context);
            //Console.WriteLine("Parameter validation (success): {0}", context.ParameterErrorMessage());

            using KeyGenerator keygen = new KeyGenerator(context);

            using PublicKey riderPub = keygen.PublicKey;
            using SecretKey riderSec = keygen.SecretKey;


            using Evaluator evaluator    = new Evaluator(context);
            using IntegerEncoder encoder = new IntegerEncoder(context);

            using Encryptor riderEncryptor = new Encryptor(context, riderPub);
            using Decryptor riderDecryptor = new Decryptor(context, riderSec);

            using Plaintext riderxPlain      = encoder.Encode(x);
            using Plaintext rideryPlain      = encoder.Encode(y);
            using Ciphertext riderxEncrypted = new Ciphertext();
            using Ciphertext rideryEncrypted = new Ciphertext();
            riderEncryptor.Encrypt(riderxPlain, riderxEncrypted);
            riderEncryptor.Encrypt(rideryPlain, rideryEncrypted);

            var fileStream = File.Create(publicFile);

            riderPub.Save(fileStream);
            fileStream.Close();

            fileStream = File.Create(secretFile);
            riderSec.Save(fileStream);
            fileStream.Close();

            fileStream = File.Create(encryptedXFile);
            riderxEncrypted.Save(fileStream);
            fileStream.Close();

            fileStream = File.Create(encryptedYFile);
            rideryEncrypted.Save(fileStream);
            fileStream.Close();
        }
Example #19
0
        // TODO these all need to be updated!

        /*
         *      0   1   2   3   4   5   6   7
         +---+---+---+---+---+---+---+---+
         | 1 | S |      Index (6+)       |
         +---+---+-----------------------+
         */
        public static bool EncodeIndexedHeaderField(int index, Span <byte> destination, out int bytesWritten)
        {
            if (destination.IsEmpty)
            {
                bytesWritten = 0;
                return(false);
            }

            EncodeHeaderBlockPrefix(destination, out bytesWritten);
            destination = destination.Slice(bytesWritten);

            return(IntegerEncoder.Encode(index, 6, destination, out bytesWritten));
        }
Example #20
0
 public static bool EncodeStaticIndexedHeaderField(int index, Span <byte> destination, out int bytesWritten)
 {
     if (!destination.IsEmpty)
     {
         destination[0] = 0b11000000;
         return(IntegerEncoder.Encode(index, 6, destination, out bytesWritten));
     }
     else
     {
         bytesWritten = 0;
         return(false);
     }
 }
Example #21
0
        /// <summary>Encodes a "Literal Header Field without Indexing".</summary>
        public static bool EncodeLiteralHeaderFieldWithNameReference(int index, string value, Span <byte> destination, out int bytesWritten)
        {
            if (destination.IsEmpty)
            {
                bytesWritten = 0;
                return(false);
            }

            EncodeHeaderBlockPrefix(destination, out bytesWritten);
            destination = destination.Slice(bytesWritten);

            return(IntegerEncoder.Encode(index, 6, destination, out bytesWritten));
        }
Example #22
0
        public static bool EncodeValueString(ReadOnlySpan <string> values, string?separator, Span <byte> buffer, out int length)
        {
            if (values.Length == 1)
            {
                return(EncodeValueString(values[0], buffer, out length));
            }

            if (values.Length == 0)
            {
                // TODO: this will be called with a string array from HttpHeaderCollection. Can we ever get a 0-length array from that? Assert if not.
                return(EncodeValueString(string.Empty, buffer, out length));
            }

            if (buffer.Length > 0)
            {
                Debug.Assert(separator != null);
                int valueLength = separator.Length * (values.Length - 1);
                for (int i = 0; i < values.Length; ++i)
                {
                    valueLength += values[i].Length;
                }

                buffer[0] = 0;
                if (IntegerEncoder.Encode(valueLength, 7, buffer, out int nameLength))
                {
                    buffer = buffer.Slice(nameLength);
                    if (buffer.Length >= valueLength)
                    {
                        string value = values[0];
                        EncodeValueStringPart(value, buffer);
                        buffer = buffer.Slice(value.Length);

                        for (int i = 1; i < values.Length; ++i)
                        {
                            EncodeValueStringPart(separator, buffer);
                            buffer = buffer.Slice(separator.Length);

                            value = values[i];
                            EncodeValueStringPart(value, buffer);
                            buffer = buffer.Slice(value.Length);
                        }

                        length = nameLength + valueLength;
                        return(true);
                    }
                }
            }

            length = 0;
            return(false);
        }
Example #23
0
        public void encryptDriverLocation(int x, int y, string publicFile, string encryptedXFile, string encryptedYFile)
        {
            //Console.WriteLine("Driver at ({0},{1})",x,y);

            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 4096;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);
            parms.PlainModulus      = new Modulus(1024);

            using SEALContext context = new SEALContext(parms);

            using KeyGenerator keygen = new KeyGenerator(context);

            using PublicKey riderPub = new PublicKey();


            using Ciphertext xEncrypted = new Ciphertext();
            using (var sr = new StreamReader(publicFile))
            {
                riderPub.Load(context, sr.BaseStream);
            }

            using Evaluator evaluator    = new Evaluator(context);
            using IntegerEncoder encoder = new IntegerEncoder(context);

            using Encryptor riderEncryptor = new Encryptor(context, riderPub);

            using Plaintext driverxPlain      = encoder.Encode(x);
            using Plaintext driveryPlain      = encoder.Encode(y);
            using Ciphertext driverxEncrypted = new Ciphertext();
            using Ciphertext driveryEncrypted = new Ciphertext();
            riderEncryptor.Encrypt(driverxPlain, driverxEncrypted);
            riderEncryptor.Encrypt(driveryPlain, driveryEncrypted);

            var fileStream = File.Create(encryptedXFile);

            driverxEncrypted.Save(fileStream);
            fileStream.Close();

            fileStream = File.Create(encryptedYFile);
            driveryEncrypted.Save(fileStream);
            fileStream.Close();
        }
Example #24
0
        public ulong decryptDistance(string publicFile, string secretFile, string distanceFile)
        {
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 4096;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);
            parms.PlainModulus      = new Modulus(1024);

            using SEALContext context = new SEALContext(parms);

            using KeyGenerator keygen = new KeyGenerator(context);

            using PublicKey riderPub = new PublicKey();
            using (var sr = new StreamReader(publicFile))
            {
                riderPub.Load(context, sr.BaseStream);
            }

            using SecretKey riderSec = new SecretKey();
            using (var sr = new StreamReader(secretFile))
            {
                riderSec.Load(context, sr.BaseStream);
            }

            using Ciphertext X2MinusX1SquaredPlusY2MinusY1Squared = new Ciphertext();
            using (var sr = new StreamReader(distanceFile))
            {
                X2MinusX1SquaredPlusY2MinusY1Squared.Load(context, sr.BaseStream);
            }

            using Encryptor riderEncryptor = new Encryptor(context, riderPub);
            using Decryptor riderDecryptor = new Decryptor(context, riderSec);


            using Plaintext distance = new Plaintext();
            riderDecryptor.Decrypt(X2MinusX1SquaredPlusY2MinusY1Squared, distance);

            using IntegerEncoder encoder = new IntegerEncoder(context);

            //Console.WriteLine("Decrypted polynomial f(x) = {0}.", distance );
            //Console.WriteLine("     distance from rider {0}", encoder.DecodeUInt64(distance));
            return(encoder.DecodeUInt64(distance));
        }
Example #25
0
        public EncCal(BigPolyArray publicKey, string polyMod, int coeffDefault, ulong plainMod)
        {
            // Create encryption parameters.
            parms = new EncryptionParameters();
            parms.PolyModulus.Set(polyMod);
            parms.CoeffModulus.Set(ChooserEvaluator.DefaultParameterOptions[coeffDefault]);
            parms.PlainModulus.Set(plainMod);
            //parms.DecompositionBitCount = 12;
            // Create encoder (for encoding and decoding)
            encoder = new IntegerEncoder(parms.PlainModulus);
            //encoder = new FractionalEncoder(parms.PlainModulus, parms.PolyModulus, 64, 32, 3);

            //Create Encryptor // not mandatory
            encryptor = new Encryptor(parms, publicKey);

            //Create Evaluator for arithmatic operations
            evaluator = new Evaluator(parms);

            CrtBuilder = new PolyCRTBuilder(parms);
        }
Example #26
0
        public void HPack_IntegerRoundTrip(int value, int bits)
        {
            var decoder = new IntegerDecoder();

            Span <byte> encoded = stackalloc byte[5];

            Assert.True(IntegerEncoder.Encode(value, bits, encoded, out int bytesWritten));

            bool finished = decoder.StartDecode(encoded[0], bits);

            int i = 1;

            for (; !finished && i < encoded.Length; ++i)
            {
                finished = decoder.Decode(encoded[i]);
            }

            Assert.True(finished);
            Assert.Equal(bytesWritten, i);
            Assert.Equal(value, decoder.Value);
        }
Example #27
0
        public static bool EncodeLiteralHeaderFieldWithStaticNameReference(int index, string value, Encoding?valueEncoding, Span <byte> destination, out int bytesWritten)
        {
            // Requires at least two bytes (one for name reference header, one for value length)
            if (destination.Length >= 2)
            {
                destination[0] = 0b01010000;
                if (IntegerEncoder.Encode(index, 4, destination, out int headerBytesWritten))
                {
                    destination = destination.Slice(headerBytesWritten);

                    if (EncodeValueString(value, valueEncoding, destination, out int valueBytesWritten))
                    {
                        bytesWritten = headerBytesWritten + valueBytesWritten;
                        return(true);
                    }
                }
            }

            bytesWritten = 0;
            return(false);
        }
Example #28
0
        private static bool EncodeValueString(string s, Span <byte> buffer, out int length)
        {
            if (buffer.Length != 0)
            {
                buffer[0] = 0;
                if (IntegerEncoder.Encode(s.Length, 7, buffer, out int nameLength))
                {
                    buffer = buffer.Slice(nameLength);
                    if (buffer.Length >= s.Length)
                    {
                        EncodeValueStringPart(s, buffer);

                        length = nameLength + s.Length;
                        return(true);
                    }
                }
            }

            length = 0;
            return(false);
        }
Example #29
0
        private static bool EncodeLiteralHeaderName(string value, Span <byte> destination, out int bytesWritten)
        {
            // From https://tools.ietf.org/html/rfc7541#section-5.2
            // ------------------------------------------------------
            //   0   1   2   3   4   5   6   7
            // +---+---+---+---+---+---+---+---+
            // | H |    String Length (7+)     |
            // +---+---------------------------+
            // |  String Data (Length octets)  |
            // +-------------------------------+

            if (!destination.IsEmpty)
            {
                destination[0] = 0; // TODO: Use Huffman encoding
                if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength))
                {
                    Debug.Assert(integerLength >= 1);

                    destination = destination.Slice(integerLength);
                    if (value.Length <= destination.Length)
                    {
                        for (int i = 0; i < value.Length; i++)
                        {
                            char c = value[i];
                            destination[i] = (byte)((uint)(c - 'A') <= ('Z' - 'A') ? c | 0x20 : c);
                        }

                        bytesWritten = integerLength + value.Length;
                        return(true);
                    }
                }
            }

            bytesWritten = 0;
            return(false);
        }
Example #30
0
 public EncCal(string polyMod, int coeffDefault, ulong plainMod, int dbc, int noOfEvaluationKeys)
 {
     // Create encryption parameters.
     parms = new EncryptionParameters();
     parms.PolyModulus.Set(polyMod);
     parms.CoeffModulus.Set(ChooserEvaluator.DefaultParameterOptions[coeffDefault]);
     parms.PlainModulus.Set(plainMod);
     // Generate keys.
     generator = new KeyGenerator(parms);
     generator.Generate(noOfEvaluationKeys);     //Integer
     // Generator contains the keys
     publicKey      = generator.PublicKey;
     secretKey      = generator.SecretKey;
     evaluationKeys = generator.EvaluationKeys;
     // Create encoder (for encoding and decoding)
     encoder = new IntegerEncoder(parms.PlainModulus);        //Integer
     //Create Encryptor
     encryptor = new Encryptor(parms, publicKey);
     //Create Decryptor
     decryptor = new Decryptor(parms, secretKey);
     //Create Evaluator for arithmatic operations
     evaluator  = new Evaluator(parms);
     CrtBuilder = new PolyCRTBuilder(parms);
 }