static async Task Main(string[] args) { Console.WriteLine("Connecting to the vote system..."); var responseMessage = await client.GetAsync("https://localhost:44319/api/vote"); Console.WriteLine("Encrypted votes received..."); var stringResponse = await responseMessage.Content.ReadAsStringAsync(); List <EncryptedVote> encryptedVotes = JsonConvert.DeserializeObject <List <EncryptedVote> >(stringResponse); SealService sealService = new SealService(); List <List <ulong> > valuesList = new List <List <ulong> >(); var items = encryptedVotes.Select(encryptedVote => SealUtils.BuildCiphertextFromBytes(encryptedVote.Data, sealService.SealContext)).ToArray(); Console.WriteLine("Create Seal evaluator... no private key needed..."); using var evaluator = sealService.CreateEvaluator(); Ciphertext results = new Ciphertext(); Console.WriteLine("Executing add function on all encrypted votes..."); evaluator.AddMany(items, results); Console.WriteLine("Finished..."); var resultsArray = SealUtils.CiphertextToArray(results); Console.WriteLine("Encrypted results serialized"); var jsonPayload = JsonConvert.SerializeObject(new { Content = resultsArray, }); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); await client.PostAsync("https://localhost:44319/api/vote/results", new StringContent(jsonPayload, Encoding.UTF8, "application/json")); Console.WriteLine("Encrypted results uploaded to the voting system"); }
public void SaveLoadTest() { SEALContext context = GlobalContext.Context; KeyGenerator keygen = new KeyGenerator(context); RelinKeys keys = keygen.RelinKeys(decompositionBitCount: 30, count: 2); Assert.IsNotNull(keys); Assert.AreEqual(30, keys.DecompositionBitCount); Assert.AreEqual(2ul, keys.Size); RelinKeys other = new RelinKeys(); MemoryPoolHandle handle = other.Pool; Assert.AreEqual(0, other.DecompositionBitCount); Assert.AreEqual(0ul, other.Size); ulong alloced = handle.AllocByteCount; using (MemoryStream ms = new MemoryStream()) { keys.Save(ms); ms.Seek(offset: 0, loc: SeekOrigin.Begin); other.Load(context, ms); } Assert.AreEqual(30, other.DecompositionBitCount); Assert.AreEqual(2ul, other.Size); Assert.IsTrue(other.IsMetadataValidFor(context)); Assert.IsTrue(handle.AllocByteCount > 0ul); List <IEnumerable <Ciphertext> > keysData = new List <IEnumerable <Ciphertext> >(keys.Data); List <IEnumerable <Ciphertext> > otherData = new List <IEnumerable <Ciphertext> >(other.Data); Assert.AreEqual(keysData.Count, otherData.Count); for (int i = 0; i < keysData.Count; i++) { List <Ciphertext> keysCiphers = new List <Ciphertext>(keysData[i]); List <Ciphertext> otherCiphers = new List <Ciphertext>(otherData[i]); Assert.AreEqual(keysCiphers.Count, otherCiphers.Count); for (int j = 0; j < keysCiphers.Count; j++) { Ciphertext keysCipher = keysCiphers[j]; Ciphertext otherCipher = otherCiphers[j]; Assert.AreEqual(keysCipher.Size, otherCipher.Size); Assert.AreEqual(keysCipher.PolyModulusDegree, otherCipher.PolyModulusDegree); Assert.AreEqual(keysCipher.CoeffModCount, otherCipher.CoeffModCount); ulong coeffCount = keysCipher.Size * keysCipher.PolyModulusDegree * keysCipher.CoeffModCount; for (ulong k = 0; k < coeffCount; k++) { Assert.AreEqual(keysCipher[k], otherCipher[k]); } } } }
public Ciphertext GetWeeklySalary(Ciphertext salary) { // Takes input as salary Ciphertext Ciphertext salaryResult = new Ciphertext(); // Multiply Plaintext constant by Ciphertext salary and store in salaryResult. Stopwatch sw = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); sw2.Start(); var num = 100000000 * 0.2; sw2.Stop(); var sw2time = sw2.Elapsed; sw.Start(); evaluator.MultiplyPlain(salary, DivideByFiftyTwo, salaryResult); sw.Stop(); var time = sw.Elapsed; return(salaryResult); }
public void DecryptAes256Ccm_returns_plaintext() { var ciphertext = Ciphertext.Skip(18).ToArray(); var iv = Ciphertext.Skip(2).Take(16).ToArray(); Assert.That(Crypto.DecryptAes256Ccm(Key, ciphertext, iv), Is.EqualTo(Plaintext)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("Processing request: Multiplication"); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); string sid = data?.sid; string matrixa = data?.matrixa; string matrixb = data?.matrixb; if (sid == null) { return(new BadRequestObjectResult("sid not present in request")); } if (matrixa == null || matrixb == null) { return(new BadRequestObjectResult("matrixa or matrixb not present in request")); } bool rlkFound = GlobalProperties.RelinKeys.TryGetValue(sid, out RelinKeys rlk); if (!rlkFound) { return(new BadRequestObjectResult("RelinKeys for given sid not found")); } Ciphertext ciphera = null; Ciphertext cipherb = null; try { ciphera = Utilities.Base64ToCiphertext(matrixa, GlobalProperties.Context); cipherb = Utilities.Base64ToCiphertext(matrixb, GlobalProperties.Context); } catch (Exception e) { return(new BadRequestObjectResult($"Error loading ciphertexts: {e.Message}")); } Ciphertext result = new Ciphertext(); try { GlobalProperties.Evaluator.Multiply(ciphera, cipherb, result); GlobalProperties.Evaluator.RelinearizeInplace(result, rlk); // Switch to smallest modulus so we save in communication GlobalProperties.Evaluator.ModSwitchToInplace(result, GlobalProperties.Context.LastParmsId); } catch (Exception e) { return(new BadRequestObjectResult($"Error computing sum: {e.Message}")); } string resultstr = $"{{ \"sid\": \"{sid}\", \"result\": \"{Utilities.CiphertextToBase64(result)}\" }}"; return(new OkObjectResult(resultstr)); }
static public List <List <Ciphertext> > extract2DCipherListFromStream(MemoryStream encryptedFeatureValuesStream, long[] columnSizes, SEALContext context) { List <List <Ciphertext> > encryptedFeatureValues = new List <List <Ciphertext> >(); int offset = 0; List <Ciphertext> curSample = new List <Ciphertext>(); foreach (long size in columnSizes) { if (size == -1) { encryptedFeatureValues.Add(curSample); curSample = new List <Ciphertext>(); continue; } Byte[] tempByteArray = new byte[(int)size]; encryptedFeatureValuesStream.Read(tempByteArray, 0, (int)size); MemoryStream tempStream = new MemoryStream(tempByteArray); tempStream.Seek(0, SeekOrigin.Begin); Ciphertext encryptedFeature = new Ciphertext(); encryptedFeature.Load(context, tempStream); tempStream.Close(); curSample.Add(encryptedFeature); offset += (int)size; } return(encryptedFeatureValues); }
static public List <List <Ciphertext> > encryptValues(List <List <float> > featureList, PublicKey pk, SEALContext context) { IntegerEncoder encoder = new IntegerEncoder(context); Encryptor encryptor = new Encryptor(context, pk); List <List <Ciphertext> > cList = new List <List <Ciphertext> >(); foreach (List <float> row in featureList) { List <Ciphertext> cRow = new List <Ciphertext>(); for (int i = 0; i < row.Count; i++) { long featureItem = (long)(row[i] * 1000); Plaintext fPlain = encoder.Encode(featureItem); Ciphertext fCipher = new Ciphertext(); encryptor.Encrypt(fPlain, fCipher); cRow.Add(fCipher); } cList.Add(cRow); } return(cList); }
/// <summary> /// Perform a Matrix operation (add / subtract) /// </summary> /// <param name="sid">Session ID</param> /// <param name="operation">Operation to perform</param> /// <param name="code">Azure Function key</param> private async Task PerformMatrixOperation(string sid, string operation, string code) { ClearLog(); Log($"Session ID: {sid}"); MatrixData mda = MatrixA.Matrix.DataContext as MatrixData; MatrixData mdb = MatrixB.Matrix.DataContext as MatrixData; Ciphertext ciphera = Utilities.MatrixToCiphertext(Utilities.MatrixDataToMatrix(mda), encryptor_, encoder_); Ciphertext cipherb = Utilities.MatrixToCiphertext(Utilities.MatrixDataToMatrix(mdb), encryptor_, encoder_); Plaintext plain = await PerformOperation(sid, operation, code, ciphera, cipherb); if (null == plain) { OperationResult.MatrixTitle = $"Error executing {operation}"; OperationResult.ClearMatrix(); return; } int rows = mda.DataView.Table.Rows.Count; int cols = mda.DataView.Table.Columns.Count; int[,] matresult = Utilities.PlaintextToMatrix(plain, rows, cols, encoder_); OperationResult.MatrixTitle = "Result"; OperationResult.InitMatrix(matresult); }
public byte[] SerializeCiphertext(Ciphertext ciphertext) { MemoryStream memoryStream = new MemoryStream(); ciphertext.Save(memoryStream); return(memoryStream.ToArray()); }
public void Create2Test() { SEALContext context = GlobalContext.BFVContext; KeyGenerator keygen1 = new KeyGenerator(context); keygen1.CreatePublicKey(out PublicKey publicKey); Encryptor encryptor1 = new Encryptor(context, publicKey); Decryptor decryptor1 = new Decryptor(context, keygen1.SecretKey); Ciphertext cipher = new Ciphertext(); Plaintext plain = new Plaintext("2x^1 + 5"); Plaintext plain2 = new Plaintext(); encryptor1.Encrypt(plain, cipher); decryptor1.Decrypt(cipher, plain2); Assert.AreNotSame(plain, plain2); Assert.AreEqual(plain, plain2); KeyGenerator keygen2 = new KeyGenerator(context, keygen1.SecretKey); keygen2.CreatePublicKey(out publicKey); Encryptor encryptor2 = new Encryptor(context, publicKey); Decryptor decryptor2 = new Decryptor(context, keygen2.SecretKey); Plaintext plain3 = new Plaintext(); decryptor2.Decrypt(cipher, plain3); Assert.AreNotSame(plain, plain3); Assert.AreEqual(plain, plain3); }
public void DecryptAes256Ccm_returns_plaintext() { var ciphertext = Ciphertext.Skip(18).ToArray(); var iv = Ciphertext.Skip(2).Take(16).ToArray(); Assert.Equal(Plaintext, Util.DecryptAes256Ccm(Key, ciphertext, iv)); }
/// <summary> /// 核对签名 /// </summary> /// <returns></returns> public bool CheckSign(out string errMsg) { if (string.IsNullOrWhiteSpace(RsaKey)) { errMsg = "rsaKey is null."; return(false); } if (string.IsNullOrWhiteSpace(Ciphertext)) { errMsg = "ciphertext is null."; return(false); } if (Timestamp == 0) { errMsg = "timestamp is null."; return(false); } if (string.IsNullOrWhiteSpace(Sign)) { errMsg = "sign is null."; return(false); } //var st = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Timestamp); //if (Math.Abs(st.Days) >= 1) { errMsg = "timestamp is error."; return false; } var txt = $"{Ciphertext.ToSafeString()}|{RsaKey.ToSafeString()}|{Timestamp.ToSafeString()}"; var hash = HashUtil.GetMd5String(txt); if (Sign.ToUpper() != hash) { errMsg = "sign is error."; return(false); } errMsg = null; return(true); }
public static List <Ciphertext> Encrypt( this byte[] data, CKKSEncoder encoder, Encryptor encryptor, double scale, int slots) { return(ComputeInBatches( data, slots, bytes => { using var pt = new Plaintext(); encoder.Encode( bytes.Select(d => Convert.ToDouble(d)), scale, pt); var ct = new Ciphertext(); encryptor.Encrypt(pt, ct); return ct; })); }
/// <summary> /// Convert a Matrix to a twisted Ciphertext. /// Rows in the matrix are laid next to each other in a Plaintext and then encrypted. /// The second batching row is duplicate of the first one but rotated by eltSeparation /// </summary> /// <param name="matrix">Matrix to convert to Ciphertext</param> /// <param name="encryptor">Encryptor used to encrypt Plaintext data</param> /// <param name="encoder">BatchEncoder used to encode the matrix data</param> /// <returns>Encrypted matrix</returns> public static Ciphertext MatrixToTwistedCiphertext(int[,] matrix, Encryptor encryptor, BatchEncoder encoder) { int batchRowSize = (int)encoder.SlotCount / 2; int rows = matrix.GetLength(dimension: 0); int cols = matrix.GetLength(dimension: 1); int paddedColLength = FindNextPowerOfTwo((ulong)rows); int eltSeparation = batchRowSize / paddedColLength; long[] batchArray = new long[encoder.SlotCount]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { batchArray[r * eltSeparation + c] = (long)matrix[r, c]; batchArray[batchRowSize + ((batchRowSize + (r - 1) * eltSeparation) % batchRowSize) + c] = (long)matrix[r, c]; } } Plaintext plain = new Plaintext(); encoder.Encode(batchArray, plain); Ciphertext result = new Ciphertext(); encryptor.Encrypt(plain, result); return(result); }
/// <summary> /// Set the indicated Matrix row as the coefficients of a Plaintext and encrypt it. /// </summary> /// <param name="matrix">Matrix to get a row from</param> /// <param name="row">Row to encrypt</param> /// <param name="repl">How many times to replicate the row values</param> /// <param name="encryptor">Encryptor used to encrypt row data</param> /// <param name="encoder">BatchEncoder used to encode the matrix data</param> /// <returns>Encrypted matrix row</returns> public static Ciphertext RowToCiphertext(int[,] matrix, int row, int repl, Encryptor encryptor, BatchEncoder encoder) { int batchRowSize = (int)encoder.SlotCount / 2; int cols = matrix.GetLength(dimension: 1); int paddedLength = FindNextPowerOfTwo((ulong)cols); int eltSeparation = batchRowSize / paddedLength; if (repl < 0 || repl > eltSeparation) { throw new ArgumentException("repl out of bounds"); } long[] rowToEncrypt = new long[batchRowSize]; for (int c = 0; c < cols; c++) { for (int j = 0; j < repl; j++) { rowToEncrypt[eltSeparation * c + j] = matrix[row, c]; } } Plaintext plain = new Plaintext(); encoder.Encode(rowToEncrypt, plain); Ciphertext result = new Ciphertext(); encryptor.Encrypt(plain, result); return(result); }
/// <summary> /// 核对签名 /// </summary> /// <returns></returns> public bool CheckSign(string modulus, string exponent, out string errMsg) { // 如果 timestamp 为0 标签没有加 [FromBody, FromForm] if (Timestamp <= 0) { errMsg = "timestamp is null."; return(false); } var st = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Timestamp); if (Math.Abs(st.TotalSeconds) >= 15) { errMsg = "timestamp is error."; return(false); } if (string.IsNullOrWhiteSpace(Ciphertext)) { errMsg = "ciphertext is null."; return(false); } if (string.IsNullOrWhiteSpace(Sign)) { errMsg = "sign is null."; return(false); } var txt = $"{Ciphertext.ToSafeString()}|{PasswordString}|{Timestamp.ToSafeString()}|{modulus}|{exponent}"; var hash = HashUtil.GetMd5String(txt); if (Sign.Equals(hash, StringComparison.OrdinalIgnoreCase) == false) { errMsg = "sign is error."; return(false); } errMsg = null; return(true); }
// Adapted from https://github.com/microsoft/SEAL/blob/master/dotnet/tests/CiphertextTests.cs#L113 static void SaveLoadTest(Func <Ciphertext, SEALContext, Ciphertext> roundtrip) { SEALContext context = GlobalContext.Context; KeyGenerator keygen = new KeyGenerator(context); Encryptor encryptor = new Encryptor(context, keygen.PublicKey); Plaintext plain = new Plaintext("2x^3 + 4x^2 + 5x^1 + 6"); Ciphertext cipher = new Ciphertext(); encryptor.Encrypt(plain, cipher); Assert.AreEqual(2ul, cipher.Size); Assert.AreEqual(8192ul, cipher.PolyModulusDegree); Assert.AreEqual(4ul, cipher.CoeffModCount); var loaded = roundtrip(cipher, context); Assert.AreEqual(2ul, loaded.Size); Assert.AreEqual(8192ul, loaded.PolyModulusDegree); Assert.AreEqual(4ul, loaded.CoeffModCount); Assert.IsTrue(ValCheck.IsValidFor(loaded, context)); ulong ulongCount = cipher.Size * cipher.PolyModulusDegree * cipher.CoeffModCount; for (ulong i = 0; i < ulongCount; i++) { Assert.AreEqual(cipher[i], loaded[i]); } }
public void EncryptTest() { SEALContext context = GlobalContext.BFVContext; KeyGenerator keyGen = new KeyGenerator(context); PublicKey publicKey = keyGen.PublicKey; SecretKey secretKey = keyGen.SecretKey; Encryptor encryptor = new Encryptor(context, publicKey, secretKey); Assert.IsNotNull(encryptor); Plaintext plain = new Plaintext("1x^1 + 1"); Ciphertext cipher = new Ciphertext(); Assert.AreEqual(0ul, cipher.Size); encryptor.Encrypt(plain, cipher); Assert.IsNotNull(cipher); Assert.AreEqual(2ul, cipher.Size); cipher = new Ciphertext(); Assert.AreEqual(0ul, cipher.Size); encryptor.Encrypt(plain, cipher); Assert.IsNotNull(cipher); Assert.AreEqual(2ul, cipher.Size); }
// private static void SinglePredict(Svc secureSvc, double[] feature, int i, CKKSEncoder encoder, Encryptor encryptor, Decryptor decryptor, Stopwatch innerProductStopwatch, Stopwatch degreeStopwatch, Stopwatch negateStopwatch, Stopwatch serverDecisionStopWatch, double scale, Result[] results) { double finalResult = 0; Console.WriteLine($"start {i} \n"); var plaintexts = new Plaintext(); var featuresCiphertexts = new Ciphertext(); encoder.Encode(feature, scale, plaintexts); encryptor.Encrypt(plaintexts, featuresCiphertexts); // Server side start var cyphetResult = secureSvc.Predict(featuresCiphertexts, true, true, innerProductStopwatch, degreeStopwatch, negateStopwatch, serverDecisionStopWatch); // Server side end //timePredictSum.Stop(); Plaintext plainResult = new Plaintext(); decryptor.Decrypt(cyphetResult, plainResult); List <double> result = new List <double>(); encoder.Decode(plainResult, result); finalResult = result[0]; int estimation = finalResult > 0 ? 0 : 1; Console.WriteLine($"\n ************************************************"); Console.WriteLine($"SVC estimation{i} is : {estimation} , result : {finalResult}"); //file.WriteLine($"{i} , {estimation} , {finalResult} "); Console.WriteLine($"************************************************ \n"); results[i] = new Result(finalResult, estimation); //Console.WriteLine($"SecureSVC estimation{i} is : {estimation} , finalResult = {finalResult} , Time = {timePredictSum.ElapsedMilliseconds}"); }
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); }
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(); }
public Ciphertext DeserializeCiphertext(byte[] data) { var memoryStream = new MemoryStream(data); var cipher = new Ciphertext(); cipher.Load(Context, memoryStream); return(cipher); }
public static Ciphertext CreateCiphertextFromInt(double value, Encryptor encryptor) { var plaintext = new Plaintext($"{value}"); var ciphertext = new Ciphertext(); encryptor.Encrypt(plaintext, ciphertext); return(ciphertext); }
public static string CiphertextToBase64String(Ciphertext ciphertext) { using (var ms = new MemoryStream()) { ciphertext.Save(ms); return(Convert.ToBase64String(ms.ToArray())); } }
protected bool Equals(CiphertextDto other) { return(Id.Equals(other.Id) && Ciphertext.SequenceEqual(other.Ciphertext) && InitializationVector.SequenceEqual(other.InitializationVector) && Salt.SequenceEqual(other.Salt) && Deleted.Equals(other.Deleted)); }
public Ciphertext GetProductivityDeficit(Ciphertext sleepHours) { //Take 8 from the value to see if a minimum of eight hours sleep has been got. Ciphertext CipherResult = new Ciphertext(); evaluator.AddPlain(sleepHours, negativeEight, CipherResult); return(CipherResult); }
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]); }
public Ciphertext GetDailyHours(Ciphertext HoursPerWeek) { Ciphertext result = new Ciphertext(); //Divides Hours per week by 5. evaluator.MultiplyPlain(HoursPerWeek, DivideByFive, result); return(result); }
public Ciphertext MultiplyBy703(Ciphertext WeightHeightDivided) { Ciphertext result = new Ciphertext(); //Takes in the weight/lbs and multiplies by 703 to get bmi. evaluator.MultiplyPlain(WeightHeightDivided, Encoded703, result); return(result); }
static async Task SendNewRun() { // Get distance from user Console.Write("Enter the new running distance (km): "); var newRunningDistance = Convert.ToInt32(Console.ReadLine()); if (newRunningDistance < 0) { Console.WriteLine("Running distance must be greater than 0."); return; } // Encrypt distance // We will convert the Int value to Hexadecimal using the ToString("X") method var plaintext = new Plaintext($"{newRunningDistance.ToString("X")}"); var ciphertextDistance = new Ciphertext(); _encryptor.Encrypt(plaintext, ciphertextDistance); // Convert value to base64 string var base64Distance = SEALUtils.CiphertextToBase64String(ciphertextDistance); // Get time from user Console.Write("Enter the new running time (hours): "); var newRunningTime = Convert.ToInt32(Console.ReadLine()); if (newRunningTime < 0) { Console.WriteLine("Running time must be greater than 0."); return; } // Encrypt time // We will convert the Int value to Hexadecimal using the ToString("X") method var plaintextTime = new Plaintext($"{newRunningTime.ToString("X")}"); var ciphertextTime = new Ciphertext(); _encryptor.Encrypt(plaintextTime, ciphertextTime); // Convert value to base64 string var base64Time = SEALUtils.CiphertextToBase64String(ciphertextTime); var metricsRequest = new RunItem { Distance = base64Distance, Time = base64Time }; LogUtils.RunItemInfo("CLIENT", "SendNewRun", metricsRequest); // Send new run to api await FitnessTrackerClient.AddNewRunningDistance(metricsRequest); }