private static void PrintAnswer(EncAnswerItem answer)
        {
            Console.WriteLine(string.Empty);
            Console.WriteLine("********* Factors *********");
            //Console.WriteLine($"Factor1:{answer.Factor1}");
            //Console.WriteLine($"Factor2:{answer.Factor2}");
            Console.WriteLine(string.Empty);

            var context           = SEALUtils.GetContext();
            var ciphertextPrime   = SEALUtils.BuildCiphertextFromBase64String(answer.Prime, context);
            var ciphertextFactor1 = SEALUtils.BuildCiphertextFromBase64String(answer.Factor1, context);
            var ciphertextFactor2 = SEALUtils.BuildCiphertextFromBase64String(answer.Factor2, context);
            var publicKey         = SEALUtils.BuildPublicKeyFromBase64String(answer.PublicKey, context);
            var secretKey         = SEALUtils.BuildSecretKeyFromBase64String(answer.SecretKey, context);

            Ciphertext temp       = new Ciphertext();
            Evaluator  _evaluator = new Evaluator(context);
            Encryptor  encryptor  = new Encryptor(context, publicKey);

            _evaluator.Multiply(ciphertextFactor1, ciphertextFactor2, temp);
            var tempstring = SEALUtils.CiphertextToBase64String(temp);

            if (tempstring.Equals(answer.Prime))
            {
                Console.WriteLine("the answer is right!");
            }
            else
            {
                var plain = new Plaintext();
                Console.WriteLine("the answer is wrong");
                Decryptor _decryptor = new Decryptor(context, secretKey);
                _decryptor.Decrypt(ciphertextPrime, plain);
                PrintAnswer(plain.ToString());
                encryptor.Encrypt(plain, temp);
                if (!SEALUtils.CiphertextToBase64String(temp).Equals(SEALUtils.CiphertextToBase64String(ciphertextPrime)))
                {
                    Console.WriteLine(SEALUtils.CiphertextToBase64String(ciphertextFactor2).Substring(0, 100));
                    Console.WriteLine(SEALUtils.CiphertextToBase64String(ciphertextFactor1).Substring(0, 100));
                }
                Console.WriteLine(_decryptor.InvariantNoiseBudget(temp));
                _decryptor.Decrypt(temp, plain);
                PrintAnswer(plain.ToString());
                //_decryptor.Decrypt(ciphertextFactor1, plain);
                //PrintAnswer(plain.ToString());
                //_decryptor.Decrypt(ciphertextFactor2, plain);
                //PrintAnswer(plain.ToString());
            }
        }
Esempio n. 2
0
        private static async Task GetMetrics()
        {
            // Get encrypted metrics
            var metrics = await FitnessTrackerClient.GetMetrics();

            LogUtils.SummaryStatisticInfo("CLIENT", "GetMetrics", metrics);

            // Decrypt the data
            var ciphertextTotalRuns = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalRuns, _context);
            var plaintextTotalRuns  = new Plaintext();

            _decryptor.Decrypt(ciphertextTotalRuns, plaintextTotalRuns);

            var ciphertextTotalDistance = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalDistance, _context);
            var plaintextTotalDistance  = new Plaintext();

            _decryptor.Decrypt(ciphertextTotalDistance, plaintextTotalDistance);

            var ciphertextTotalHours = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalHours, _context);
            var plaintextTotalHours  = new Plaintext();

            _decryptor.Decrypt(ciphertextTotalHours, plaintextTotalHours);


            // Print metrics in console
            PrintMetrics(plaintextTotalRuns.ToString(), plaintextTotalDistance.ToString(), plaintextTotalHours.ToString());
        }
Esempio n. 3
0
        public void BatchUnbatchPlaintextNET()
        {
            var parms = new EncryptionParameters();

            parms.PolyModulus  = "1x^64 + 1";
            parms.CoeffModulus = new List <SmallModulus> {
                DefaultParams.SmallMods60Bit(0)
            };
            parms.PlainModulus = 257;

            var context = new SEALContext(parms);

            Assert.IsTrue(context.Qualifiers.EnableBatching);

            var crtbuilder = new PolyCRTBuilder(context);

            Assert.AreEqual(64, crtbuilder.SlotCount);
            var plain = new Plaintext(crtbuilder.SlotCount);

            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                plain[i] = (UInt64)i;
            }

            crtbuilder.Compose(plain);
            crtbuilder.Decompose(plain);
            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                Assert.IsTrue(plain[i] == (UInt64)i);
            }

            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                plain[i] = (UInt64)5;
            }
            crtbuilder.Compose(plain);
            Assert.IsTrue(plain.ToString().Equals("5"));
            crtbuilder.Decompose(plain);
            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                Assert.IsTrue(plain[i] == (UInt64)5);
            }

            var short_plain = new Plaintext(20);

            for (int i = 0; i < 20; i++)
            {
                short_plain[i] = (UInt64)i;
            }
            crtbuilder.Compose(short_plain);
            crtbuilder.Decompose(short_plain);
            for (int i = 0; i < 20; i++)
            {
                Assert.IsTrue(short_plain[i] == (UInt64)i);
            }
            for (int i = 20; i < crtbuilder.SlotCount; i++)
            {
                Assert.IsTrue(short_plain[i] == 0UL);
            }
        }
Esempio n. 4
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();
        }
Esempio n. 5
0
        public void ToStringTest()
        {
            Plaintext plain = new Plaintext(coeffCount: 6);

            plain[0] = 1;
            plain[1] = 2;
            plain[2] = 3;
            plain[3] = 4;
            plain[4] = 5;
            plain[5] = 6;

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

            string str = plain.ToString();

            Assert.AreEqual("6x^5 + 5x^4 + 4x^3 + 3x^2 + 2x^1 + 1", str);
        }
Esempio n. 6
0
        public void EncodeLongTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);

            parms.PolyModulusDegree = 64;
            parms.CoeffModulus      = CoeffModulus.Create(64, new int[] { 60 });
            parms.PlainModulus      = new Modulus(257);

            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);

            BatchEncoder encoder = new BatchEncoder(context);

            Assert.AreEqual(64ul, encoder.SlotCount);

            List <long> plainList = new List <long>();

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                plainList.Add((long)i);
            }

            Plaintext plain = new Plaintext();

            encoder.Encode(plainList, plain);

            List <long> plainList2 = new List <long>();

            encoder.Decode(plain, plainList2);

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(plainList[checked ((int)i)], plainList2[checked ((int)i)]);
            }

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                plainList[checked ((int)i)] = 5;
            }

            encoder.Encode(plainList, plain);
            Assert.AreEqual("5", plain.ToString());

            encoder.Decode(plain, plainList2);

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(plainList[checked ((int)i)], plainList2[checked ((int)i)]);
            }

            List <long> shortList = new List <long>();

            for (int i = 0; i < 20; i++)
            {
                shortList.Add((long)i);
            }

            encoder.Encode(shortList, plain);

            List <long> shortList2 = new List <long>();

            encoder.Decode(plain, shortList2);

            Assert.AreEqual(20, shortList.Count);
            Assert.AreEqual(64, shortList2.Count);

            for (int i = 0; i < 20; i++)
            {
                Assert.AreEqual(shortList[i], shortList2[i]);
            }

            for (ulong i = 20; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(0L, shortList2[checked ((int)i)]);
            }
        }
Esempio n. 7
0
        private static void HomoExample()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);

            parms.PolyModulusDegree = 2048;
            parms.CoeffModulus      = DefaultParams.CoeffModulus128(polyModulusDegree: 2048);
            parms.PlainModulus      = new SmallModulus(1 << 8);
            SEALContext    context = SEALContext.Create(parms);
            IntegerEncoder encoder = new IntegerEncoder(context);

            KeyGenerator keygen = new KeyGenerator(context);

            Microsoft.Research.SEAL.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);

            int       value1 = 5;
            Plaintext plain1 = encoder.Encode(value1);

            Console.WriteLine($"Encoded {value1} as polynomial {plain1.ToString()} (plain1)");

            int       value2 = -7;
            Plaintext plain2 = encoder.Encode(value2);

            Console.WriteLine($"Encoded {value2} as polynomial {plain2.ToString()} (plain2)");

            Ciphertext encrypted1 = new Ciphertext();
            Ciphertext encrypted2 = new Ciphertext();

            Console.Write("Encrypting plain1: ");

            encryptor.Encrypt(plain1, encrypted1);
            Console.WriteLine("Done (encrypted1)");

            Plaintext plainResult = new Plaintext();

            decryptor.Decrypt(encrypted1, plainResult);
            Console.WriteLine(encoder.DecodeInt32(plainResult));


            Console.Write("Encrypting plain2: ");
            encryptor.Encrypt(plain2, encrypted2);
            Console.WriteLine("Done (encrypted2)");



            Console.WriteLine($"Noise budget in encrypted1: {decryptor.InvariantNoiseBudget(encrypted1)} bits");
            Console.WriteLine($"Noise budget in encrypted2: {decryptor.InvariantNoiseBudget(encrypted2)} bits");

            evaluator.NegateInplace(encrypted1);
            Console.WriteLine($"Noise budget in -encrypted1: {decryptor.InvariantNoiseBudget(encrypted1)} bits");

            evaluator.AddInplace(encrypted1, encrypted2);

            Console.WriteLine($"Noise budget in -encrypted1 + encrypted2: {decryptor.InvariantNoiseBudget(encrypted1)} bits");

            evaluator.MultiplyInplace(encrypted1, encrypted2);

            Console.WriteLine($"Noise budget in (-encrypted1 + encrypted2) * encrypted2: {decryptor.InvariantNoiseBudget(encrypted1)} bits");

            plainResult = new Plaintext();
            Console.Write("Decrypting result: ");
            decryptor.Decrypt(encrypted1, plainResult);
            Console.WriteLine("Done");

            Console.WriteLine($"Plaintext polynomial: {plainResult.ToString()}");

            Console.WriteLine($"Decoded integer: {encoder.DecodeInt32(plainResult)}");
        }
Esempio n. 8
0
        static async Task RunAsync()
        {
            // Update port # in the following line.
            client.BaseAddress = new Uri("http://localhost/");
            //client.BaseAddress = new Uri("https://sealserver20200623225403.azurewebsites.net/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/octet-stream"));
            UriBuilder builder = new UriBuilder();

            builder.Port = 50755;
            builder.Path = "sealoperation";
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 4096;

            parms.PolyModulusDegree   = polyModulusDegree;
            parms.CoeffModulus        = CoeffModulus.BFVDefault(polyModulusDegree);
            parms.PlainModulus        = new Modulus(4096);
            using SEALContext context = new SEALContext(parms);
            using Evaluator evaluator = new Evaluator(context);
            using KeyGenerator keygen = new KeyGenerator(context);
            using PublicKey publicKey = keygen.PublicKey;
            using SecretKey secretKey = keygen.SecretKey;
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Decryptor decryptor = new Decryptor(context, secretKey);


            //BigInteger bint = BigInteger.Parse("97391909619002370737223511047161666878854921822310726371156754097341907215981");
            BigInteger bint = BigInteger.Parse("998745113");
            //int xVal = 625;
            //int degree = 10;
            //int coeff = 25;
            // These are good starting points for small numbers < 100mil

            /*
             * int tConst = 121;
             * int xVal = 10;
             * int degree = 2;
             * int coeff = 3;
             */
            int tConst = 1210;
            int xVal   = 25;
            int degree = 4;
            int coeff  = 3;


            // Candidate first result from initial polynomial
            List <int> terms;
            BigInteger res = createBigIntFromPoly(degree, coeff, xVal, tConst, out terms);

            // compare res to target BigInteger, if way smaller, then create a new
            // result after increasing any of the polynomial values
            while (BigInteger.Compare(res, bint) < 0) // res is less than bint
            {
                BigInteger halfVal    = BigInteger.Divide(bint, new BigInteger(2));
                BigInteger onePercent = BigInteger.Divide(bint, new BigInteger(100));
                BigInteger tenPercent = BigInteger.Multiply(onePercent, new BigInteger(10));
                //BigInteger quarterVal = BigInteger.Divide(bint, new BigInteger(4));
                if (BigInteger.Compare(halfVal, res) > 0)
                {
                    //coeff += 1;
                    int len  = halfVal.ToString().Length;
                    int len2 = res.ToString().Length;
                    if (len == len2)
                    {
                        coeff *= 2;
                    }
                    else
                    {
                        degree += 2;
                    }
                    res = createBigIntFromPoly(degree, coeff, xVal, tConst, out terms);
                }
                else
                {
                    BigInteger difference = BigInteger.Subtract(bint, res);
                    if (BigInteger.Compare(tenPercent, difference) > 0)
                    {
                        tConst += 1111;
                    }
                    else
                    {
                        coeff += 1;
                    }
                    res = createBigIntFromPoly(degree, coeff, xVal, tConst, out terms);
                }
                //Console.WriteLine(res.ToString());
                Console.WriteLine("...");
            }
            // Res is now equal or greater to bint
            tConst = tConst - (int)BigInteger.Subtract(res, bint);
            // Now check the polynomial
            BigInteger testPoly = createBigIntFromPoly(degree, coeff, xVal, tConst, out terms);

            Console.WriteLine("For Big Integer {0}", bint.ToString());
            foreach (int term in terms)
            {
                Console.WriteLine("Polynomial term is {0}x^{1}", coeff, term);
            }
            Console.WriteLine("Final term is constant {0} with x={1}", tConst, xVal);
            byte[] bytespan = bint.ToByteArray();
            byte[] newspan  = new byte[bytespan.Length];
            newspan[0] = bytespan[0];
            BigInteger binttemp = new BigInteger(bytespan);
            // Pick an 'x' value for the polynomial that is big enough to represent the upper 10 digits of the value
            BigInteger bint2   = BigInteger.Parse("7983012132846067729184195556448685457666384473549591845215215701504271855338012801306119587019479688581971723759499902125851173348207536911525267617909811");
            BigInteger bintres = bint * bint2;

            using Plaintext bPlainB = new Plaintext(bint.ToString());
            int x = 9;

            Console.WriteLine("Plain x value to set");
            Console.WriteLine(x.ToString());
            using Plaintext xPlainX = new Plaintext(Convert.ToString(x, 16));
            Console.WriteLine("Hex value being set");
            Console.WriteLine(xPlainX.ToString());
            using Ciphertext xEncrypted = new Ciphertext();
            Console.WriteLine("Encrypt xPlain to xEncrypted.");
            encryptor.Encrypt(xPlainX, xEncrypted);
            int y = 5;

            Console.WriteLine("Plain y value to set");
            Console.WriteLine(y.ToString());
            using Plaintext xPlainY = new Plaintext(Convert.ToString(y, 16));
            Console.WriteLine("Hex y value being set");
            Console.WriteLine(xPlainY.ToString());
            using Ciphertext yEncrypted = new Ciphertext();
            encryptor.Encrypt(xPlainY, yEncrypted);

            FHEParams fHEParams = new FHEParams();

            fHEParams.param1 = xEncrypted;
            fHEParams.param2 = yEncrypted;
            fHEParams.result = new Ciphertext();
            // DEBUG ONLY
            Ciphertext mAnswer = new Ciphertext();

            evaluator.Multiply(fHEParams.param1, fHEParams.param2, mAnswer);
            evaluator.Add(fHEParams.param1, fHEParams.param2, fHEParams.result);
            string expAnswer = SerializeSEAL(fHEParams.result);

            using Plaintext xDecrypted2 = new Plaintext();
            decryptor.Decrypt(mAnswer, xDecrypted2);
            Console.WriteLine(xDecrypted2.ToString());
            decryptor.Decrypt(fHEParams.result, xDecrypted2);
            string answer = xDecrypted2.ToString();
            int    num    = 0;

            Int32.TryParse(answer, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num);
            Console.WriteLine("Local answer");
            Console.WriteLine(answer);
            Console.WriteLine(num.ToString());

            // END DEBUG

            //fHEParams.param1.

            fHEParams.operation = "add";

            SEALTransport transport = new SEALTransport();

            transport.ContextParams = SerializeSEAL(parms);

            transport.FHEParam1 = SerializeSEAL(fHEParams.param1);
            // Console.WriteLine(transport.FHEParam1);
            transport.FHEParam2 = SerializeSEAL(fHEParams.param2);
            transport.FHEResult = SerializeSEAL(fHEParams.result);
            transport.Operation = fHEParams.operation;

            try
            {
                // Get the parameters,
                SEALTransport response = await PostFHEResultAsync(builder.Uri.AbsoluteUri, transport);

                Ciphertext result    = new Ciphertext();
                byte[]     fp1       = System.Convert.FromBase64String(response.FHEResult);
                string     recAnswer = response.FHEResult;
                if (expAnswer == recAnswer)
                {
                    Console.WriteLine("Expected answer matches received answer");
                }
                MemoryStream mst = new MemoryStream(fp1);
                result.Load(context, mst);
                Plaintext xDecrypted3 = new Plaintext();
                decryptor.Decrypt(result, xDecrypted3);
                answer = xDecrypted3.ToString();
                Console.WriteLine(answer);
                Console.WriteLine("Remote Decimal answer");
                Int32.TryParse(answer, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num);
                Console.WriteLine(num.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
Esempio n. 9
0
        public void EncodeLongTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);

            parms.PolyModulusDegree = 64;
            List <SmallModulus> coeffModulus = new List <SmallModulus>();

            coeffModulus.Add(DefaultParams.SmallMods60Bit(0));
            parms.CoeffModulus = coeffModulus;
            parms.PlainModulus = new SmallModulus(257);

            SEALContext context = SEALContext.Create(parms);

            BatchEncoder encoder = new BatchEncoder(context);

            Assert.AreEqual(64ul, encoder.SlotCount);

            List <long> plainList = new List <long>();

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                plainList.Add((long)i);
            }

            Plaintext plain = new Plaintext();

            encoder.Encode(plainList, plain);

            List <long> plainList2 = new List <long>();

            encoder.Decode(plain, plainList2);

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(plainList[(int)i], plainList2[(int)i]);
            }

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                plainList[(int)i] = 5;
            }

            encoder.Encode(plainList, plain);
            Assert.AreEqual("5", plain.ToString());

            encoder.Decode(plain, plainList2);

            for (ulong i = 0; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(plainList[(int)i], plainList2[(int)i]);
            }

            List <long> shortList = new List <long>();

            for (int i = 0; i < 20; i++)
            {
                shortList.Add((long)i);
            }

            encoder.Encode(shortList, plain);

            List <long> shortList2 = new List <long>();

            encoder.Decode(plain, shortList2);

            Assert.AreEqual(20, shortList.Count);
            Assert.AreEqual(64, shortList2.Count);

            for (int i = 0; i < 20; i++)
            {
                Assert.AreEqual(shortList[i], shortList2[i]);
            }

            for (ulong i = 20; i < encoder.SlotCount; i++)
            {
                Assert.AreEqual(0L, shortList2[(int)i]);
            }
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);

            parms.PolyModulusDegree = 4096;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(4096);
            parms.PlainModulus      = new Modulus(4096 * 2);


            SEALContext context = new SEALContext(new EncryptionParameters(parms));

            Console.WriteLine(context.ParameterErrorMessage());
            KeyGenerator keygen    = new KeyGenerator(context);
            PublicKey    publicKey = new PublicKey(keygen.PublicKey);
            SecretKey    secretKey = new SecretKey(keygen.SecretKey);

            Encryptor encryptor = new Encryptor(context, publicKey);

            Evaluator evaluator = new Evaluator(context);

            Decryptor decryptor = new Decryptor(context, secretKey);


            Console.WriteLine("Generate locally usable relinearization keys.");
            using RelinKeys relinKeys = keygen.RelinKeysLocal();

            int x = 6;

            using Plaintext xPlain = new Plaintext(x.ToString());

            using Ciphertext xEncrypted = new Ciphertext();
            encryptor.Encrypt(xPlain, xEncrypted);
            using Ciphertext xSqPlusOne      = new Ciphertext();
            using Plaintext decryptedResult  = new Plaintext();
            using Ciphertext xPlusOneSq      = new Ciphertext();
            using Ciphertext encryptedResult = new Ciphertext();
            using Plaintext plainOne         = new Plaintext("1");
            using Plaintext plainFour        = new Plaintext("4");

            /*
             * We now repeat the computation relinearizing after each multiplication.
             */

            Console.WriteLine("Compute and relinearize xSquared (x^2),");
            Console.WriteLine(new string(' ', 13) + "then compute xSqPlusOne (x^2+1)");
            using Ciphertext xSquared = new Ciphertext();
            evaluator.Square(xEncrypted, xSquared);
            Console.WriteLine($"    + size of xSquared: {xSquared.Size}");
            evaluator.RelinearizeInplace(xSquared, relinKeys);
            Console.WriteLine("    + size of xSquared (after relinearization): {0}",
                              xSquared.Size);
            evaluator.AddPlain(xSquared, plainOne, xSqPlusOne);
            Console.WriteLine("    + noise budget in xSqPlusOne: {0} bits",
                              decryptor.InvariantNoiseBudget(xSqPlusOne));
            Console.Write("    + decryption of xSqPlusOne: ");
            decryptor.Decrypt(xSqPlusOne, decryptedResult);
            int q = Convert.ToInt32(decryptedResult.ToString(), 16);

            Console.WriteLine($"{q} ...... Correct.");
            //Console.WriteLine($"0x{decryptedResult} ...... Correct.");


            using Ciphertext xPlusOne = new Ciphertext();
            Console.WriteLine("Compute xPlusOne (x+1),");
            Console.WriteLine(new string(' ', 13) +
                              "then compute and relinearize xPlusOneSq ((x+1)^2).");
            evaluator.AddPlain(xEncrypted, plainOne, xPlusOne);
            evaluator.Square(xPlusOne, xPlusOneSq);
            Console.WriteLine($"    + size of xPlusOneSq: {xPlusOneSq.Size}");
            evaluator.RelinearizeInplace(xPlusOneSq, relinKeys);
            Console.WriteLine("    + noise budget in xPlusOneSq: {0} bits",
                              decryptor.InvariantNoiseBudget(xPlusOneSq));
            Console.Write("    + decryption of xPlusOneSq: ");
            decryptor.Decrypt(xPlusOneSq, decryptedResult);
            int r = Convert.ToInt32(decryptedResult.ToString(), 16);

            Console.WriteLine($"{r} ...... Correct.");


            Console.WriteLine("Compute and relinearize encryptedResult (4(x^2+1)(x+1)^2).");
            evaluator.MultiplyPlainInplace(xSqPlusOne, plainFour);
            evaluator.Multiply(xSqPlusOne, xPlusOneSq, encryptedResult);
            Console.WriteLine($"    + size of encryptedResult: {encryptedResult.Size}");
            evaluator.RelinearizeInplace(encryptedResult, relinKeys);
            Console.WriteLine("    + size of encryptedResult (after relinearization): {0}",
                              encryptedResult.Size);
            Console.WriteLine("    + noise budget in encryptedResult: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedResult));

            Console.WriteLine();
            Console.WriteLine("NOTE: Notice the increase in remaining noise budget.");

            /*
             * Relinearization clearly improved our noise consumption. We have still plenty
             * of noise budget left, so we can expect the correct answer when decrypting.
             */

            Console.WriteLine("Decrypt encrypted_result (4(x^2+1)(x+1)^2).");
            decryptor.Decrypt(encryptedResult, decryptedResult);
            int t = Convert.ToInt32(decryptedResult.ToString(), 16);

            Console.WriteLine("    + decryption of 4(x^2+1)(x+1)^2 = 0x{0} ...... Correct.", t);


            Plaintext  four           = new Plaintext("4");
            Plaintext  four1          = new Plaintext("5");
            Ciphertext fourEncrypted  = new Ciphertext();
            Ciphertext four1Encrypted = new Ciphertext();

            encryptor.Encrypt(four, fourEncrypted);
            encryptor.Encrypt(four1, four1Encrypted);

            Ciphertext d = new Ciphertext();

            evaluator.Sub(fourEncrypted, four1Encrypted, d);
            Plaintext temp = new Plaintext();

            decryptor.Decrypt(d, temp);

            Console.WriteLine($"{Convert.ToInt32(temp.ToString(), 16)}");
        }
Esempio n. 11
0
        public void Calculation(double step, int m, string func, TcpClient client)
        {
            Dispatcher.BeginInvoke(new ThreadStart(delegate {
                Canvas.Children.Clear();
                AxisInit(m);
            }));

            points = new List <List <Point> >();

            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);

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


            SEALContext  context   = new SEALContext(new EncryptionParameters(parms));
            KeyGenerator keygen    = new KeyGenerator(context);
            PublicKey    publicKey = keygen.PublicKey;
            SecretKey    secretKey = keygen.SecretKey;

            Encryptor encryptor = new Encryptor(context, publicKey);

            Decryptor decryptor = new Decryptor(context, secretKey);

            MemoryStream streamParms = new MemoryStream();
            MemoryStream streamSk    = new MemoryStream();

            secretKey.Save(streamSk);
            parms.Save(streamParms);

            byte[] spbuff = streamParms.GetBuffer();

            client.Client.Send(spbuff);

            byte[] count = Encoding.ASCII.GetBytes(Convert.ToInt32(Canvas.ActualWidth + step).ToString());
            client.Client.Send(count);

            byte[] func_buffer = Encoding.ASCII.GetBytes(func);
            client.Client.Send(func_buffer);

            byte[] offset_buffer = Encoding.ASCII.GetBytes((0).ToString());
            client.Client.Send(offset_buffer);

            int x = -(int)Canvas.ActualWidth / 2;

            for (int i = 0; i <= (int)(Canvas.ActualWidth / step); i += 1)
            {
                Plaintext data = new Plaintext();
                string    temp = (i).ToString();
                bool      sign;
                if (x >= 0)
                {
                    data = new Plaintext(x.ToString());
                    sign = false;
                }
                else
                {
                    data = new Plaintext(Math.Abs(x).ToString());
                    sign = true;
                }


                Ciphertext dataEncrypted = new Ciphertext();

                encryptor.Encrypt(data, dataEncrypted);


                byte[] sbuff;

                MemoryStream streamEncrypted = new MemoryStream();
                dataEncrypted.Save(streamEncrypted);
                sbuff = streamEncrypted.GetBuffer();

                client.Client.Send(sbuff);
                streamEncrypted.Close();


                byte[] bufferRecieved = new byte[9377792 * 2];
                dataEncrypted = new Ciphertext();

                client.Client.Receive(bufferRecieved);
                MemoryStream streamRecieved = new MemoryStream(bufferRecieved);
                Ciphertext   c = new Ciphertext();
                c.Load(context, streamRecieved);
                dataEncrypted = c;


                data = new Plaintext();
                decryptor.Decrypt(dataEncrypted, data);



                streamParms.Close();
                streamSk.Close();

                double f;
                string t = data.ToString();
                f = Convert.ToInt32(data.ToString(), 16);

                List <Point> p  = new List <Point>();
                int          ep = 0;
                Dispatcher.BeginInvoke(new ThreadStart(delegate { ep = (int)scale_bar.Maximum + 1; }));
                Thread.Sleep(10);

                if (sign)
                {
                    x = -Math.Abs(x);
                    //f = -Math.Abs(f);
                }

                for (int k = 1; k < ep; k++)
                {
                    //p.Add(new Point((i - (int)Canvas.ActualWidth / 2) * k, (f + Canvas.ActualHeight / 2) * k));
                    p.Add(new Point((x) * k + Canvas.ActualWidth / 2, f * k + Canvas.ActualHeight / 2));
                }

                points.Add(p);

                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    if (i > 1 && points.Count > 1 && i < points.Count)
                    {
                        Lines(points[i - 1][(int)(scale_bar.Value - 1)], points[i][(int)(scale_bar.Value - 1)]);
                    }
                }));

                if (x < Canvas.ActualWidth / 2)
                {
                    x += (int)step;
                }
            }

            client.Client.Disconnect(true);

            /////
            /////
            /////
            //for (int i = 0; i < points.Count - 1; i++)
            //{
            //    Lines(points[i][(int)(scale_bar.Value - 1)], points[i + 1][(int)(scale_bar.Value - 1)]);
            //}
            /////
            /////
            /////
        }
Esempio n. 12
0
        public void BatchUnbatchIntVectorNET()
        {
            var parms = new EncryptionParameters();

            parms.PolyModulus  = "1x^64 + 1";
            parms.CoeffModulus = new List <SmallModulus> {
                DefaultParams.SmallMods60Bit(0)
            };
            parms.PlainModulus = 257;

            var context = new SEALContext(parms);

            Assert.IsTrue(context.Qualifiers.EnableBatching);

            var crtbuilder = new PolyCRTBuilder(context);

            Assert.AreEqual(64, crtbuilder.SlotCount);
            var plain_vec = new List <Int64>();

            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                plain_vec.Add((Int64)i * (1 - 2 * (i % 2)));
            }

            var plain = new Plaintext();

            crtbuilder.Compose(plain_vec, plain);
            var plain_vec2 = new List <Int64>();

            crtbuilder.Decompose(plain, plain_vec2);
            Assert.IsTrue(plain_vec.SequenceEqual(plain_vec2));

            for (int i = 0; i < crtbuilder.SlotCount; i++)
            {
                plain_vec[i] = -5;
            }
            crtbuilder.Compose(plain_vec, plain);
            Assert.IsTrue(plain.ToString().Equals("FC"));
            crtbuilder.Decompose(plain, plain_vec2);
            Assert.IsTrue(plain_vec.SequenceEqual(plain_vec2));

            var short_plain_vec = new List <Int64>();

            for (int i = 0; i < 20; i++)
            {
                short_plain_vec.Add((Int64)i * (1 - 2 * (i % 2)));
            }
            crtbuilder.Compose(short_plain_vec, plain);
            var short_plain_vec2 = new List <Int64>();

            crtbuilder.Decompose(plain, short_plain_vec2);
            Assert.AreEqual(20, short_plain_vec.Count);
            Assert.AreEqual(64, short_plain_vec2.Count);
            for (int i = 0; i < 20; i++)
            {
                Assert.AreEqual(short_plain_vec[i], short_plain_vec2[i]);
            }
            for (int i = 20; i < crtbuilder.SlotCount; i++)
            {
                Assert.AreEqual(0L, short_plain_vec2[i]);
            }
        }