Esempio n. 1
0
        public void CreateTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 64,
                PlainModulus      = new Modulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            SecretKey secret = keygen.SecretKey;
            SecretKey copy   = new SecretKey(secret);

            Assert.AreEqual(64ul, copy.Data.CoeffCount);
            Assert.IsTrue(copy.Data.IsNTTForm);

            SecretKey copy2 = new SecretKey();

            copy2.Set(copy);

            Assert.AreEqual(64ul, copy2.Data.CoeffCount);
            Assert.IsTrue(copy2.Data.IsNTTForm);
        }
Esempio n. 2
0
        public void KeyStepTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 64,
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 60, 60 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            GaloisKeys keys = keygen.GaloisKeys(steps: new int[] { 1, 2, 3 });

            Assert.IsNotNull(keys);

            Assert.AreEqual(3ul, keys.Size);

            Assert.IsFalse(keys.HasKey(1));
            Assert.IsTrue(keys.HasKey(3));
            Assert.IsFalse(keys.HasKey(5));
            Assert.IsFalse(keys.HasKey(7));
            Assert.IsTrue(keys.HasKey(9));
            Assert.IsFalse(keys.HasKey(11));
            Assert.IsFalse(keys.HasKey(13));
            Assert.IsFalse(keys.HasKey(15));
            Assert.IsFalse(keys.HasKey(17));
            Assert.IsFalse(keys.HasKey(19));
            Assert.IsFalse(keys.HasKey(21));
            Assert.IsFalse(keys.HasKey(23));
            Assert.IsFalse(keys.HasKey(25));
            Assert.IsTrue(keys.HasKey(27));
        }
Esempio n. 3
0
        public void EncodeDecodeDoubleTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            parms.PolyModulusDegree = 64;
            parms.CoeffModulus      = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 });
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);

            int            slots  = 16;
            Plaintext      plain  = new Plaintext();
            double         delta  = 1 << 16;
            List <Complex> result = new List <Complex>();

            CKKSEncoder encoder = new CKKSEncoder(context);

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

            double value = 10d;

            encoder.Encode(value, delta, plain);
            encoder.Decode(plain, result);

            for (int i = 0; i < slots; i++)
            {
                double tmp = Math.Abs(value - result[i].Real);
                Assert.IsTrue(tmp < 0.5);
            }
        }
Esempio n. 4
0
        public void EncodeDecodeVectorDoubleTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 64,
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 30, 30 })
            };

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

            double[] values = new double[] { 0.1, 2.3, 34.4 };
            encoder.Encode(values, scale: Math.Pow(2, 20), destination: plain);

            List <double> result = new List <double>();

            encoder.Decode(plain, result);

            Assert.IsNotNull(result);
            Assert.AreEqual(0.1, result[0], delta: 0.001);
            Assert.AreEqual(2.3, result[1], delta: 0.001);
            Assert.AreEqual(34.4, result[2], delta: 0.001);
        }
Esempio n. 5
0
        public void ExceptionsTest()
        {
            SEALContext  context = GlobalContext.BFVContext;
            KeyGenerator keygen  = new KeyGenerator(context);
            SecretKey    secret  = new SecretKey();
            List <uint>  elts    = new List <uint> {
                16385
            };
            List <uint> elts_null = null;
            List <int>  steps     = new List <int> {
                4096
            };
            List <int> steps_null = null;

            Utilities.AssertThrows <ArgumentNullException>(() => keygen = new KeyGenerator(null));

            Utilities.AssertThrows <ArgumentNullException>(() => keygen = new KeyGenerator(context, null));
            Utilities.AssertThrows <ArgumentNullException>(() => keygen = new KeyGenerator(null, keygen.SecretKey));
            Utilities.AssertThrows <ArgumentException>(() => keygen     = new KeyGenerator(context, secret));

            Utilities.AssertThrows <ArgumentNullException>(() => keygen.CreateGaloisKeys(elts_null));
            Utilities.AssertThrows <ArgumentException>(() => keygen.CreateGaloisKeys(elts));
            Utilities.AssertThrows <ArgumentNullException>(() => keygen.CreateGaloisKeys(steps_null));
            Utilities.AssertThrows <ArgumentException>(() => keygen.CreateGaloisKeys(steps));

            EncryptionParameters smallParms = new EncryptionParameters(SchemeType.CKKS);

            smallParms.PolyModulusDegree = 128;
            smallParms.CoeffModulus      = CoeffModulus.Create(smallParms.PolyModulusDegree, new int[] { 60 });
            context = new SEALContext(smallParms, true, SecLevelType.None);
            keygen  = new KeyGenerator(context);
            Utilities.AssertThrows <InvalidOperationException>(() => keygen.CreateRelinKeys());
            Utilities.AssertThrows <InvalidOperationException>(() => keygen.CreateGaloisKeys());
        }
Esempio n. 6
0
        public void EncodeDecodeComplexTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 64,
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 })
            };

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

            Plaintext plain = new Plaintext();
            Complex   value = new Complex(3.1415, 2.71828);

            encoder.Encode(value, scale: Math.Pow(2, 20), destination: plain);

            List <Complex> result = new List <Complex>();

            encoder.Decode(plain, result);

            Assert.IsTrue(result.Count > 0);
            Assert.AreEqual(3.1415, result[0].Real, delta: 0.0001);
            Assert.AreEqual(2.71828, result[0].Imaginary, delta: 0.0001);
        }
Esempio n. 7
0
        public void EncodeDecodeUlongTest()
        {
            int slots = 32;
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            parms.PolyModulusDegree = (ulong)slots * 2;
            parms.CoeffModulus      = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 });
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            CKKSEncoder encoder = new CKKSEncoder(context);

            Plaintext      plain  = new Plaintext();
            List <Complex> result = new List <Complex>();

            long value = 15;

            encoder.Encode(value, plain);
            encoder.Decode(plain, result);

            for (int i = 0; i < slots; i++)
            {
                double tmp = Math.Abs(value - result[i].Real);
                Assert.IsTrue(tmp < 0.5);
            }
        }
Esempio n. 8
0
        public void CreateTest()
        {
            List <Modulus> cm = (List <Modulus>)CoeffModulus.Create(2, new int[] { });

            Assert.AreEqual(0, cm.Count);

            cm = (List <Modulus>)CoeffModulus.Create(2, new int[] { 3 });
            Assert.AreEqual(1, cm.Count);
            Assert.AreEqual(5ul, cm[0].Value);

            cm = (List <Modulus>)CoeffModulus.Create(2, new int[] { 3, 4 });
            Assert.AreEqual(2, cm.Count);
            Assert.AreEqual(5ul, cm[0].Value);
            Assert.AreEqual(13ul, cm[1].Value);

            cm = (List <Modulus>)CoeffModulus.Create(2, new int[] { 3, 5, 4, 5 });
            Assert.AreEqual(4, cm.Count);
            Assert.AreEqual(5ul, cm[0].Value);
            Assert.AreEqual(17ul, cm[1].Value);
            Assert.AreEqual(13ul, cm[2].Value);
            Assert.AreEqual(29ul, cm[3].Value);

            cm = (List <Modulus>)CoeffModulus.Create(32, new int[] { 30, 40, 30, 30, 40 });
            Assert.AreEqual(5, cm.Count);
            Assert.AreEqual(30, (int)(Math.Log(cm[0].Value, 2)) + 1);
            Assert.AreEqual(40, (int)(Math.Log(cm[1].Value, 2)) + 1);
            Assert.AreEqual(30, (int)(Math.Log(cm[2].Value, 2)) + 1);
            Assert.AreEqual(30, (int)(Math.Log(cm[3].Value, 2)) + 1);
            Assert.AreEqual(40, (int)(Math.Log(cm[4].Value, 2)) + 1);
            Assert.AreEqual(1ul, cm[0].Value % 64);
            Assert.AreEqual(1ul, cm[1].Value % 64);
            Assert.AreEqual(1ul, cm[2].Value % 64);
            Assert.AreEqual(1ul, cm[3].Value % 64);
            Assert.AreEqual(1ul, cm[4].Value % 64);
        }
Esempio n. 9
0
        public void ExceptionsTest()
        {
            Modulus sm = new Modulus(0x12345ul);

            Utilities.AssertThrows <ArgumentNullException>(() => sm = new Modulus(null));
            Utilities.AssertThrows <ArgumentNullException>(() => sm.Set(null));
            Utilities.AssertThrows <ArgumentNullException>(() => sm.Save(null));
            Utilities.AssertThrows <ArgumentNullException>(() => sm.Load(null));
            Utilities.AssertThrows <EndOfStreamException>(() => sm.Load(new MemoryStream()));

            // Too small polyModulusDegree
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(1, new int[] { 2 }));

            // Too large polyModulusDegree
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(262144, new int[] { 30 }));

            // Invalid polyModulusDegree
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(1023, new int[] { 20 }));

            // Invalid bitSize
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { 0 }));
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { -30 }));
            Utilities.AssertThrows <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { 30, -30 }));

            // Too small primes requested
            Utilities.AssertThrows <InvalidOperationException>(() => CoeffModulus.Create(2, new int[] { 2 }));
            Utilities.AssertThrows <InvalidOperationException>(() => CoeffModulus.Create(2, new int[] { 3, 3, 3 }));
            Utilities.AssertThrows <InvalidOperationException>(() => CoeffModulus.Create(1024, new int[] { 8 }));
        }
Esempio n. 10
0
        public void ScaleTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 8,
                CoeffModulus      = CoeffModulus.Create(8, new int[] { 40, 40, 40, 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: true,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            keygen.CreatePublicKey(out PublicKey publicKey);
            keygen.CreateGaloisKeys(out GaloisKeys galoisKeys);

            Encryptor   encryptor = new Encryptor(context, publicKey);
            Evaluator   evaluator = new Evaluator(context);
            CKKSEncoder encoder   = new CKKSEncoder(context);

            MemoryPoolHandle pool = MemoryManager.GetPool(MMProfOpt.ForceNew);

            Assert.AreEqual(0ul, pool.AllocByteCount);

            Ciphertext encrypted = new Ciphertext(pool);
            Plaintext  plain     = new Plaintext();

            MemoryPoolHandle cipherPool = encrypted.Pool;

            Assert.IsNotNull(cipherPool);
            Assert.AreEqual(0ul, cipherPool.AllocByteCount);

            List <Complex> input = new List <Complex>()
            {
                new Complex(1, 1),
                new Complex(2, 2),
                new Complex(3, 3),
                new Complex(4, 4)
            };
            double delta = Math.Pow(2, 70);

            encoder.Encode(input, context.FirstParmsId, delta, plain);
            encryptor.Encrypt(plain, encrypted);

            Assert.AreEqual(delta, encrypted.Scale, delta: Math.Pow(2, 60));

            Ciphertext encrypted2 = new Ciphertext();

            encrypted2.Set(encrypted);
            Assert.AreEqual(delta, encrypted2.Scale, delta: Math.Pow(2, 60));

            evaluator.RescaleToNextInplace(encrypted);

            Assert.AreEqual(Math.Pow(2, 30), encrypted.Scale, delta: 10000);
            Assert.AreNotEqual(0ul, cipherPool.AllocByteCount);

            double newScale = Math.Pow(2, 10);

            encrypted.Scale = newScale;
            Assert.AreEqual(newScale, encrypted.Scale, delta: 100);
        }
Esempio n. 11
0
        public void SeededKeyTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 128,
                PlainModulus      = new Modulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(128, new int[] { 40, 40, 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            RelinKeys relinKeys = new RelinKeys();

            using (MemoryStream stream = new MemoryStream())
            {
                keygen.CreateRelinKeys().Save(stream);
                stream.Seek(0, SeekOrigin.Begin);
                relinKeys.Load(context, stream);
            }

            keygen.CreatePublicKey(out PublicKey publicKey);
            Encryptor encryptor = new Encryptor(context, publicKey);
            Decryptor decryptor = new Decryptor(context, keygen.SecretKey);
            Evaluator evaluator = new Evaluator(context);

            Ciphertext encrypted1 = new Ciphertext(context);
            Ciphertext encrypted2 = new Ciphertext(context);
            Plaintext  plain1     = new Plaintext();
            Plaintext  plain2     = new Plaintext();

            plain1.Set(0);
            encryptor.Encrypt(plain1, encrypted1);
            evaluator.SquareInplace(encrypted1);
            evaluator.RelinearizeInplace(encrypted1, relinKeys);
            decryptor.Decrypt(encrypted1, plain2);

            Assert.AreEqual(1ul, plain2.CoeffCount);
            Assert.AreEqual(0ul, plain2[0]);

            plain1.Set("1x^10 + 2");
            encryptor.Encrypt(plain1, encrypted1);
            evaluator.SquareInplace(encrypted1);
            evaluator.RelinearizeInplace(encrypted1, relinKeys);
            evaluator.SquareInplace(encrypted1);
            evaluator.Relinearize(encrypted1, relinKeys, encrypted2);
            decryptor.Decrypt(encrypted2, plain2);

            // {1x^40 + 8x^30 + 18x^20 + 20x^10 + 10}
            Assert.AreEqual(41ul, plain2.CoeffCount);
            Assert.AreEqual(16ul, plain2[0]);
            Assert.AreEqual(32ul, plain2[10]);
            Assert.AreEqual(24ul, plain2[20]);
            Assert.AreEqual(8ul, plain2[30]);
            Assert.AreEqual(1ul, plain2[40]);
        }
Esempio n. 12
0
        public void SEALContextParamsTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 128,
                PlainModulus      = new SmallModulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(128, new int[] { 30, 30, 30 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: true,
                                                  secLevel: SecLevelType.None);

            SEALContext.ContextData data = context.KeyContextData;
            Assert.IsNotNull(data);

            EncryptionParameters parms2 = data.Parms;

            Assert.AreEqual(parms.PolyModulusDegree, parms2.PolyModulusDegree);

            EncryptionParameterQualifiers qualifiers = data.Qualifiers;

            Assert.IsNotNull(qualifiers);

            Assert.IsTrue(qualifiers.ParametersSet);
            Assert.IsFalse(qualifiers.UsingBatching);
            Assert.IsTrue(qualifiers.UsingFastPlainLift);
            Assert.IsTrue(qualifiers.UsingFFT);
            Assert.IsTrue(qualifiers.UsingNTT);
            Assert.AreEqual(SecLevelType.None, qualifiers.SecLevel);
            Assert.IsFalse(qualifiers.UsingDescendingModulusChain);
            Assert.IsTrue(context.UsingKeyswitching);

            ulong[] cdpm = data.CoeffDivPlainModulus;
            Assert.AreEqual(3, cdpm.Length);

            Assert.AreEqual(32ul, data.PlainUpperHalfThreshold);

            Assert.AreEqual(3, data.PlainUpperHalfIncrement.Length);
            Assert.IsNull(data.UpperHalfThreshold);
            Assert.IsNotNull(data.UpperHalfIncrement);
            Assert.AreEqual(3, data.UpperHalfIncrement.Length);
            Assert.AreEqual(2ul, data.ChainIndex);

            Assert.IsNull(data.PrevContextData);
            SEALContext.ContextData data2 = data.NextContextData;
            Assert.IsNotNull(data2);
            Assert.AreEqual(1ul, data2.ChainIndex);
            Assert.AreEqual(2ul, data2.PrevContextData.ChainIndex);

            SEALContext.ContextData data3 = data2.NextContextData;
            Assert.IsNotNull(data3);
            Assert.AreEqual(0ul, data3.ChainIndex);
            Assert.AreEqual(1ul, data3.PrevContextData.ChainIndex);
            Assert.IsNull(data3.NextContextData);
        }
Esempio n. 13
0
 public SalaryComputation()
 {
     //Constructor.
     parms = new EncryptionParameters(SchemeType.CKKS);
     parms.PolyModulusDegree = polyModulusDegree;
     parms.CoeffModulus      = CoeffModulus.Create(
         polyModulusDegree, new int[] { 60, 40, 40, 60 });
     //parms.PlainModulus = PlainModulus.Batching(polyModulusDegree, 20);
     context   = new SEALContext(parms);
     evaluator = new Evaluator(context);
     encoder   = new CKKSEncoder(context);
     SetConstants();
 }
Esempio n. 14
0
        public void CreateTest()
        {
            {
                EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
                {
                    PolyModulusDegree = 64,
                    PlainModulus      = new Modulus(1 << 6),
                    CoeffModulus      = CoeffModulus.Create(64, new int[] { 40 })
                };
                SEALContext context = new SEALContext(parms,
                                                      expandModChain: false,
                                                      secLevel: SecLevelType.None);
                KeyGenerator keygen = new KeyGenerator(context);
                keygen.CreatePublicKey(out PublicKey pub);
                PublicKey copy = new PublicKey(pub);

                Assert.IsNotNull(copy);
                Assert.AreEqual(2ul, copy.Data.Size);
                Assert.IsTrue(copy.Data.IsNTTForm);

                PublicKey copy2 = new PublicKey();
                copy2.Set(copy);

                Assert.AreEqual(2ul, copy2.Data.Size);
                Assert.IsTrue(copy2.Data.IsNTTForm);
            }
            {
                EncryptionParameters parms = new EncryptionParameters(SchemeType.BGV)
                {
                    PolyModulusDegree = 64,
                    PlainModulus      = new Modulus(1 << 6),
                    CoeffModulus      = CoeffModulus.Create(64, new int[] { 40 })
                };
                SEALContext context = new SEALContext(parms,
                                                      expandModChain: false,
                                                      secLevel: SecLevelType.None);
                KeyGenerator keygen = new KeyGenerator(context);
                keygen.CreatePublicKey(out PublicKey pub);
                PublicKey copy = new PublicKey(pub);

                Assert.IsNotNull(copy);
                Assert.AreEqual(2ul, copy.Data.Size);
                Assert.IsTrue(copy.Data.IsNTTForm);

                PublicKey copy2 = new PublicKey();
                copy2.Set(copy);

                Assert.AreEqual(2ul, copy2.Data.Size);
                Assert.IsTrue(copy2.Data.IsNTTForm);
            }
        }
Esempio n. 15
0
        public void EqualsTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 8,
                PlainModulus      = new SmallModulus(257),
                CoeffModulus      = CoeffModulus.Create(8, new int[] { 40, 40 })
            };

            EncryptionParameters parms2 = new EncryptionParameters(SchemeType.CKKS);

            Assert.AreNotEqual(parms, parms2);
            Assert.IsFalse(parms.Equals(null));
        }
Esempio n. 16
0
			//private static bool _firstTime = true;

            //private static Decryptor _decryptor;

            public SecureSvc(int nRows, double[][] vectors, double[][] coefficients, double[] intercepts,
				 String kernel, double gamma, double coef0, ulong degree , int power)
			{


				//this._nRows			= nRows;

				this._vectors		= vectors;
				this._coefficients	= coefficients;
				this._intercepts		= intercepts;

				this._kernel			= Enum.Parse<Kernel>(kernel, true);
				this._gamma			= gamma;
				this._coef0			= coef0;
				this._degree			= degree;
				this._power			= power;
				EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

				ulong polyModulusDegree = 16384;
				
				if (power >= 20 && power < 40 )
				{
					parms.CoeffModulus = CoeffModulus.Create(polyModulusDegree,
						new int[] { 60, 20, 21, 22, 23, 24, 25, 26, 27, 60 });
				}
				else if (power >= 40 && power < 60)
				{
					parms.CoeffModulus = CoeffModulus.Create(polyModulusDegree,
						new int[] { 60, 40, 40, 40, 40, 40, 40, 40 , 60 });
				}
				else if (power == 60)
				{
					polyModulusDegree = 32768;
                    parms.CoeffModulus = CoeffModulus.Create(polyModulusDegree,
						new int[] { 60, 60, 60, 60, 60, 60, 60, 60, 60 });
				}
				parms.PolyModulusDegree = polyModulusDegree;
                _context = new SEALContext(parms);

				KeyGenerator keygen = new KeyGenerator(_context);
				_publicKey = keygen.PublicKey;
				_secretKey = keygen.SecretKey;
				_relinKeys = keygen.RelinKeys();
				_galoisKeys = keygen.GaloisKeys();

				_encryptor = new Encryptor(_context, _publicKey);
				_evaluator = new Evaluator(_context);
				_decryptor = new Decryptor(_context, _secretKey);
				_encoder = new CKKSEncoder(_context);
			}
 public BMIComputation(RelinKeys Keys)
 {
     parms = new EncryptionParameters(SchemeType.CKKS);
     parms.PolyModulusDegree = polyModulusDegree;
     parms.CoeffModulus      = CoeffModulus.Create(
         polyModulusDegree, new int[] { 60, 40, 40, 60 });
     //parms.PlainModulus = PlainModulus.Batching(polyModulusDegree, 20);
     context   = new SEALContext(parms);
     evaluator = new Evaluator(context);
     encoder   = new CKKSEncoder(context);
     scale     = Math.Pow(2.0, 40);
     SetConstants();
     KeysRelin = Keys;
 }
Esempio n. 18
0
        public void SaveLoadTest()
        {
            TestDelegate save_load_test = delegate(SchemeType scheme)
            {
                List <SmallModulus>  coeffModulus = (List <SmallModulus>)CoeffModulus.Create(8, new int[] { 40, 40 });
                EncryptionParameters parms        = new EncryptionParameters(scheme)
                {
                    PolyModulusDegree = 8,
                    CoeffModulus      = coeffModulus
                };
                if (scheme == SchemeType.BFV)
                {
                    parms.SetPlainModulus(257);
                }

                EncryptionParameters loaded = null;

                using (MemoryStream stream = new MemoryStream())
                {
                    EncryptionParameters.Save(parms, stream);

                    stream.Seek(offset: 0, loc: SeekOrigin.Begin);

                    loaded = EncryptionParameters.Load(stream);
                }

                Assert.AreEqual(scheme, loaded.Scheme);
                Assert.AreEqual(8ul, loaded.PolyModulusDegree);
                if (scheme == SchemeType.BFV)
                {
                    Assert.AreEqual(257ul, loaded.PlainModulus.Value);
                }
                else if (scheme == SchemeType.CKKS)
                {
                    Assert.AreEqual(0ul, loaded.PlainModulus.Value);
                }

                List <SmallModulus> loadedCoeffModulus = new List <SmallModulus>(loaded.CoeffModulus);
                Assert.AreEqual(2, loadedCoeffModulus.Count);
                Assert.AreNotSame(coeffModulus[0], loadedCoeffModulus[0]);
                Assert.AreNotSame(coeffModulus[1], loadedCoeffModulus[1]);
                Assert.AreEqual(coeffModulus[0], loadedCoeffModulus[0]);
                Assert.AreEqual(coeffModulus[1], loadedCoeffModulus[1]);
            };

            save_load_test(SchemeType.BFV);
            save_load_test(SchemeType.CKKS);
        }
Esempio n. 19
0
 public CKKSEncryptor()
 {
     //Set scheme Primes and encryption parameters.
     parms = new EncryptionParameters(SchemeType.CKKS);
     parms.PolyModulusDegree = polyModulusDegree;
     parms.CoeffModulus      = CoeffModulus.Create(
         polyModulusDegree, new int[] { 60, 40, 40, 60 });
     scale   = Math.Pow(2.0, 40);
     context = new SEALContext(parms);
     keygen  = new KeyGenerator(context);
     //Generate private and public key.
     publicKey = keygen.PublicKey;
     secretKey = keygen.SecretKey;
     encryptor = new Encryptor(context, publicKey);
     encoder   = new CKKSEncoder(context);
     KeysRelin = keygen.RelinKeys();
 }
Esempio n. 20
0
        public void SchemeIsCKKSTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 8,
                CoeffModulus      = CoeffModulus.Create(8, new int[] { 40, 40, 40, 40 })
            };

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

            Utilities.AssertThrows <ArgumentException>(() =>
            {
                BatchEncoder encoder = new BatchEncoder(context);
            });
        }
Esempio n. 21
0
        public void ExceptionsTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 64,
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 60 }),
                PlainModulus      = new Modulus(257)
            };

            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            BatchEncoder     enc         = new BatchEncoder(context);
            List <ulong>     valu        = new List <ulong>();
            List <ulong>     valu_null   = null;
            List <long>      vall        = new List <long>();
            List <long>      vall_null   = null;
            Plaintext        plain       = new Plaintext();
            Plaintext        plain_null  = null;
            MemoryPoolHandle pool_uninit = new MemoryPoolHandle();

            Utilities.AssertThrows <ArgumentNullException>(() => enc = new BatchEncoder(null));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Encode(valu, plain_null));
            Utilities.AssertThrows <ArgumentNullException>(() => enc.Encode(valu_null, plain));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Encode(vall, plain_null));
            Utilities.AssertThrows <ArgumentNullException>(() => enc.Encode(vall_null, plain));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Encode(plain_null));
            Utilities.AssertThrows <ArgumentException>(() => enc.Encode(plain, pool_uninit));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Decode(plain, valu_null));
            Utilities.AssertThrows <ArgumentNullException>(() => enc.Decode(plain_null, valu));
            Utilities.AssertThrows <ArgumentException>(() => enc.Decode(plain, valu, pool_uninit));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Decode(plain, vall_null));
            Utilities.AssertThrows <ArgumentNullException>(() => enc.Decode(plain_null, vall));
            Utilities.AssertThrows <ArgumentException>(() => enc.Decode(plain, vall, pool_uninit));

            Utilities.AssertThrows <ArgumentNullException>(() => enc.Decode(plain_null));
            Utilities.AssertThrows <ArgumentException>(() => enc.Decode(plain, pool_uninit));
        }
Esempio n. 22
0
        public void SaveLoadTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 64,
                PlainModulus      = new SmallModulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            SecretKey secret = keygen.SecretKey;

            Assert.AreEqual(64ul, secret.Data.CoeffCount);
            Assert.IsTrue(secret.Data.IsNTTForm);
            Assert.AreNotEqual(ParmsId.Zero, secret.ParmsId);

            SecretKey        secret2 = new SecretKey();
            MemoryPoolHandle handle  = secret2.Pool;

            Assert.IsNotNull(secret2);
            Assert.AreEqual(0ul, secret2.Data.CoeffCount);
            Assert.IsFalse(secret2.Data.IsNTTForm);
            ulong alloced = handle.AllocByteCount;

            using (MemoryStream stream = new MemoryStream())
            {
                secret.Save(stream);

                stream.Seek(offset: 0, loc: SeekOrigin.Begin);

                secret2.Load(context, stream);
            }

            Assert.AreNotSame(secret, secret2);
            Assert.AreEqual(64ul, secret2.Data.CoeffCount);
            Assert.IsTrue(secret2.Data.IsNTTForm);
            Assert.AreNotEqual(ParmsId.Zero, secret2.ParmsId);
            Assert.AreEqual(secret.ParmsId, secret2.ParmsId);
            Assert.IsTrue(handle.AllocByteCount != alloced);
        }
Esempio n. 23
0
        public void SaveLoadTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 64,
                PlainModulus      = new Modulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            KeyGenerator keygen = new KeyGenerator(context);

            PublicKey pub = keygen.PublicKey;

            Assert.IsNotNull(pub);
            Assert.AreEqual(2ul, pub.Data.Size);
            Assert.IsTrue(pub.Data.IsNTTForm);

            PublicKey        pub2   = new PublicKey();
            MemoryPoolHandle handle = pub2.Pool;

            Assert.AreEqual(0ul, pub2.Data.Size);
            Assert.IsFalse(pub2.Data.IsNTTForm);
            Assert.AreEqual(ParmsId.Zero, pub2.ParmsId);

            using (MemoryStream stream = new MemoryStream())
            {
                pub.Save(stream);

                stream.Seek(offset: 0, loc: SeekOrigin.Begin);

                pub2.Load(context, stream);
            }

            Assert.AreNotSame(pub, pub2);
            Assert.AreEqual(2ul, pub2.Data.Size);
            Assert.IsTrue(pub2.Data.IsNTTForm);
            Assert.AreEqual(pub.ParmsId, pub2.ParmsId);
            Assert.AreNotEqual(ParmsId.Zero, pub2.ParmsId);
            Assert.IsTrue(handle.AllocByteCount != 0ul);
        }
Esempio n. 24
0
        public void BGVParameterErrorTest()
        {
            SEALContext context = GlobalContext.BGVContext;
            EncryptionParameterQualifiers qualifiers = context.FirstContextData.Qualifiers;

            Assert.AreEqual(qualifiers.ParametersErrorName(), "success");
            Assert.AreEqual(qualifiers.ParametersErrorMessage(), "valid");

            EncryptionParameters encParam = new EncryptionParameters(SchemeType.BGV)
            {
                PolyModulusDegree = 127,
                PlainModulus      = new Modulus(1 << 6),
                CoeffModulus      = CoeffModulus.Create(128, new int[] { 30, 30, 30 })
            };

            context    = new SEALContext(encParam, expandModChain: true, secLevel: SecLevelType.None);
            qualifiers = context.FirstContextData.Qualifiers;
            Assert.AreEqual(qualifiers.ParametersErrorName(), "invalid_poly_modulus_degree_non_power_of_two");
            Assert.AreEqual(qualifiers.ParametersErrorMessage(), "poly_modulus_degree is not a power of two");
        }
Esempio n. 25
0
        public void ExceptionsTest()
        {
            // Too small polyModulusDegree
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(1, new int[] { 2 }));

            // Too large polyModulusDegree
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(65536, new int[] { 30 }));

            // Invalid polyModulusDegree
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(1023, new int[] { 20 }));

            // Invalid bitSize
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { 0 }));
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { -30 }));
            Assert.ThrowsException <ArgumentException>(() => CoeffModulus.Create(2048, new int[] { 30, -30 }));

            // Too small primes requested
            Assert.ThrowsException <InvalidOperationException>(() => CoeffModulus.Create(2, new int[] { 2 }));
            Assert.ThrowsException <InvalidOperationException>(() => CoeffModulus.Create(2, new int[] { 3, 3, 3 }));
            Assert.ThrowsException <InvalidOperationException>(() => CoeffModulus.Create(1024, new int[] { 8 }));
        }
Esempio n. 26
0
        public void SEALContextCKKSParamsTest()
        {
            int slotSize = 4;
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                PolyModulusDegree = 2 * (ulong)slotSize,
                CoeffModulus      = CoeffModulus.Create(2 * (ulong)slotSize, new int[] { 40, 40, 40, 40 })
            };
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: true,
                                                  secLevel: SecLevelType.None);

            SEALContext.ContextData data = context.KeyContextData;
            Assert.IsNotNull(data);

            // This should be available in CKKS
            Assert.IsNotNull(data.UpperHalfThreshold);
            Assert.AreEqual(4, data.UpperHalfThreshold.Length);
            Assert.IsNull(data.UpperHalfIncrement);
            Assert.AreEqual(3ul, data.ChainIndex);

            Assert.IsNull(data.PrevContextData);
            SEALContext.ContextData data2 = data.NextContextData;
            Assert.IsNotNull(data2);
            Assert.AreEqual(2ul, data2.ChainIndex);
            Assert.AreEqual(3ul, data2.PrevContextData.ChainIndex);

            SEALContext.ContextData data3 = data2.NextContextData;
            Assert.IsNotNull(data3);
            Assert.AreEqual(1ul, data3.ChainIndex);
            Assert.AreEqual(2ul, data3.PrevContextData.ChainIndex);

            SEALContext.ContextData data4 = data3.NextContextData;
            Assert.IsNotNull(data4);
            Assert.AreEqual(0ul, data4.ChainIndex);
            Assert.AreEqual(1ul, data4.PrevContextData.ChainIndex);

            Assert.IsNull(data4.NextContextData);
        }
Esempio n. 27
0
        public void EncodeInPlaceTest()
        {
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV)
            {
                PolyModulusDegree = 64,
                CoeffModulus      = CoeffModulus.Create(64, new int[] { 60 }),
                PlainModulus      = new Modulus(257)
            };

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

            BatchEncoder encoder = new BatchEncoder(context);

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

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

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

            encoder.Encode(plain);

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

            encoder.Decode(plain);
            Assert.AreEqual(64ul, plain.CoeffCount);

            for (ulong i = 0; i < 6; i++)
            {
                Assert.AreEqual((i + 1), plain[i]);
            }

            for (ulong i = 6; i < plain.CoeffCount; i++)
            {
                Assert.AreEqual(0ul, plain[i]);
            }
        }
        public ImageProcessorClient()
        {
            parms = new EncryptionParameters(SchemeType.CKKS);
            parms.PolyModulusDegree = (ulong)PolyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.Create((ulong)PolyModulusDegree, new int[] { 60, 40, 40, 60 });

            double scale = Math.Pow(2.0, 40);

            context = new SEALContext(parms);

            keygen    = new KeyGenerator(context);
            secretKey = keygen.SecretKey;
            keygen.CreatePublicKey(out PublicKey publicKey);

            // keygen.CreateRelinKeys(out RelinKeys relinKeys);

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

            encoder = new CKKSEncoder(context);

            var v1 = Enumerable.Range(0, 2000).Select(e => (double)200);
            var v2 = Enumerable.Range(0, 4000).Select(e => (double)200);
            var v3 = Enumerable.Range(0, 4096).Select(e => (double)200);

            var pd1 = new Plaintext();
            var pd2 = new Plaintext();
            var pd3 = new Plaintext();

            //encoder.Encode(v1, scale, pd1);
            //encoder.Encode(v1, scale, pd2);
            //encoder.Encode(v1, scale, pd3);

            // Pass in encode and evaluator to server.
            _imageProcessorServer = new ImageProcessorServer(evaluator, encoder, scale);
        }
Esempio n. 29
0
        public void EncodeDecodeVectorTest()
        {
            int slots = 32;
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            parms.PolyModulusDegree = (ulong)slots * 2;
            parms.CoeffModulus      = CoeffModulus.Create((ulong)slots * 2, new int[] { 60, 60, 60, 60 });
            SEALContext context = new SEALContext(parms,
                                                  expandModChain: false,
                                                  secLevel: SecLevelType.None);
            CKKSEncoder encoder = new CKKSEncoder(context);

            List <Complex> values    = new List <Complex>(slots);
            Random         rnd       = new Random();
            int            dataBound = 1 << 30;
            double         delta     = 1ul << 40;

            for (int i = 0; i < slots; i++)
            {
                values.Add(new Complex(rnd.Next() % dataBound, 0));
            }

            Plaintext plain = new Plaintext();

            encoder.Encode(values, delta, plain);

            List <Complex> result = new List <Complex>();

            encoder.Decode(plain, result);

            for (int i = 0; i < slots; i++)
            {
                double tmp = Math.Abs(values[i].Real - result[i].Real);
                Assert.IsTrue(tmp < 0.5);
            }
        }
Esempio n. 30
0
        static private void ExampleCKKSEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / CKKS Encoder");

            /*
             * [CKKSEncoder] (For CKKS scheme only)
             *
             * In this example we demonstrate the Cheon-Kim-Kim-Song (CKKS) scheme for
             * computing on encrypted real or complex numbers. We start by creating
             * encryption parameters for the CKKS scheme. There are two important
             * differences compared to the BFV scheme:
             *
             *  (1) CKKS does not use the PlainModulus encryption parameter;
             *  (2) Selecting the CoeffModulus in a specific way can be very important
             *      when using the CKKS scheme. We will explain this further in the file
             *      `CKKS_Basics.cs'. In this example we use CoeffModulus.Create to
             *      generate 5 40-bit prime numbers.
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            ulong polyModulusDegree = 8192;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.Create(
                polyModulusDegree, new int[] { 40, 40, 40, 40, 40 });

            /*
             * We create the SEALContext as usual and print the parameters.
             */
            using SEALContext context = new SEALContext(parms);
            Utilities.PrintParameters(context);
            Console.WriteLine();

            /*
             * Keys are created the same way as for the BFV scheme.
             */
            using KeyGenerator keygen = new KeyGenerator(context);
            using SecretKey secretKey = keygen.SecretKey;
            keygen.CreatePublicKey(out PublicKey publicKey);
            keygen.CreateRelinKeys(out RelinKeys relinKeys);

            /*
             * We also set up an Encryptor, Evaluator, and Decryptor as usual.
             */
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Evaluator evaluator = new Evaluator(context);
            using Decryptor decryptor = new Decryptor(context, secretKey);

            /*
             * To create CKKS plaintexts we need a special encoder: there is no other way
             * to create them. The BatchEncoder cannot be used with the
             * CKKS scheme. The CKKSEncoder encodes vectors of real or complex numbers into
             * Plaintext objects, which can subsequently be encrypted. At a high level this
             * looks a lot like what BatchEncoder does for the BFV scheme, but the theory
             * behind it is completely different.
             */
            using CKKSEncoder encoder = new CKKSEncoder(context);

            /*
             * In CKKS the number of slots is PolyModulusDegree / 2 and each slot encodes
             * one real or complex number. This should be contrasted with BatchEncoder in
             * the BFV scheme, where the number of slots is equal to PolyModulusDegree
             * and they are arranged into a matrix with two rows.
             */
            ulong slotCount = encoder.SlotCount;

            Console.WriteLine($"Number of slots: {slotCount}");

            /*
             * We create a small vector to encode; the CKKSEncoder will implicitly pad it
             * with zeros to full size (PolyModulusDegree / 2) when encoding.
             */
            double[] input = new double[] { 0.0, 1.1, 2.2, 3.3 };
            Console.WriteLine("Input vector: ");
            Utilities.PrintVector(input);

            /*
             * Now we encode it with CKKSEncoder. The floating-point coefficients of `input'
             * will be scaled up by the parameter `scale'. This is necessary since even in
             * the CKKS scheme the plaintext elements are fundamentally polynomials with
             * integer coefficients. It is instructive to think of the scale as determining
             * the bit-precision of the encoding; naturally it will affect the precision of
             * the result.
             *
             * In CKKS the message is stored modulo CoeffModulus (in BFV it is stored modulo
             * PlainModulus), so the scaled message must not get too close to the total size
             * of CoeffModulus. In this case our CoeffModulus is quite large (200 bits) so
             * we have little to worry about in this regard. For this simple example a 30-bit
             * scale is more than enough.
             */
            using Plaintext plain = new Plaintext();
            double scale = Math.Pow(2.0, 30);

            Utilities.PrintLine();
            Console.WriteLine("Encode input vector.");
            encoder.Encode(input, scale, plain);

            /*
             * We can instantly decode to check the correctness of encoding.
             */
            List <double> output = new List <double>();

            Console.WriteLine("    + Decode input vector ...... Correct.");
            encoder.Decode(plain, output);
            Utilities.PrintVector(output);

            /*
             * The vector is encrypted the same was as in BFV.
             */
            using Ciphertext encrypted = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Encrypt input vector, square, and relinearize.");
            encryptor.Encrypt(plain, encrypted);

            /*
             * Basic operations on the ciphertexts are still easy to do. Here we square
             * the ciphertext, decrypt, decode, and print the result. We note also that
             * decoding returns a vector of full size (PolyModulusDegree / 2); this is
             * because of the implicit zero-padding mentioned above.
             */
            evaluator.SquareInplace(encrypted);
            evaluator.RelinearizeInplace(encrypted, relinKeys);

            /*
             * We notice that the scale in the result has increased. In fact, it is now
             * the square of the original scale: 2^60.
             */
            Console.WriteLine("    + Scale in squared input: {0} ({1} bits)",
                              encrypted.Scale,
                              (int)Math.Ceiling(Math.Log(encrypted.Scale, newBase: 2)));
            Utilities.PrintLine();
            Console.WriteLine("Decrypt and decode.");
            decryptor.Decrypt(encrypted, plain);
            encoder.Decode(plain, output);
            Console.WriteLine("    + Result vector ...... Correct.");
            Utilities.PrintVector(output);

            /*
             * The CKKS scheme allows the scale to be reduced between encrypted computations.
             * This is a fundamental and critical feature that makes CKKS very powerful and
             * flexible. We will discuss it in great detail in `3_Levels.cs' and later in
             * `4_CKKS_Basics.cs'.
             */
        }