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()); }
public bool IsIn(Position searchPosition) { var encoded = GetEncodedPosition(searchPosition); var evaluator = new Evaluator(GetContext()); PositionEncrypted positionEncrypted = GetFromIota(); evaluator.SubPlain(positionEncrypted.Lon, encoded.Lon); evaluator.SubPlain(positionEncrypted.Lat, encoded.Lat); var decryptor = new Decryptor(GetContext(), GetSecretKey()); Plaintext plainResultLon = new Plaintext(); Plaintext plainResultLat = new Plaintext(); decryptor.Decrypt(positionEncrypted.Lon, plainResultLon); decryptor.Decrypt(positionEncrypted.Lat, plainResultLat); var encoder = GetEncoder(GetContext()); double resultLon = encoder.Decode(plainResultLon); double resultLat = encoder.Decode(plainResultLat); var diff = Math.Abs(resultLon) + Math.Abs(resultLat); if (diff < 0.007) { return(true); } return(false); }
public void EncryptExponentiateDecryptNET() { var parms = new EncryptionParameters { DecompositionBitCount = 4, NoiseStandardDeviation = 3.19, NoiseMaxDeviation = 35.06 }; var coeffModulus = parms.CoeffModulus; coeffModulus.Resize(48); coeffModulus.Set("FFFFFFFFC001"); var plainModulus = parms.PlainModulus; plainModulus.Resize(7); plainModulus.Set(1 << 4); var polyModulus = parms.PolyModulus; polyModulus.Resize(64, 1); polyModulus[0].Set(1); polyModulus[63].Set(1); var keygen = new KeyGenerator(parms); keygen.Generate(); var Encoder = new BinaryEncoder(parms.PlainModulus); var encryptor = new Encryptor(parms, keygen.PublicKey); var evaluator = new Evaluator(parms, keygen.EvaluationKeys); var keygenEvals = keygen.EvaluationKeys; var evaluatorEvals = keygen.EvaluationKeys; for (int i = 0; i < keygen.EvaluationKeys.Count; ++i) { Assert.AreEqual(keygenEvals[i], evaluatorEvals[i]); } var decryptor = new Decryptor(parms, keygen.SecretKey); var encrypted = encryptor.Encrypt(Encoder.Encode(5)); var power = evaluator.Exponentiate(encrypted, 1); Assert.AreEqual(5, Encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(Encoder.Encode(5)); power = evaluator.Exponentiate(encrypted, 0); Assert.AreEqual(1, Encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(Encoder.Encode(5)); power = evaluator.Exponentiate(encrypted, 0); Assert.AreEqual(1, Encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(Encoder.Encode(7)); power = evaluator.Exponentiate(encrypted, 2); Assert.AreEqual(49, Encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(Encoder.Encode(-7)); power = evaluator.Exponentiate(encrypted, 3); Assert.AreEqual(-343, Encoder.DecodeInt32(decryptor.Decrypt(power))); }
public void TransformEncryptedToFromNTTNET() { var parms = new EncryptionParameters(MemoryPoolHandle.AcquireNew()); parms.SetDecompositionBitCount(4); parms.SetNoiseStandardDeviation(3.19); parms.SetNoiseMaxDeviation(35.06); var coeffModulus = new BigUInt(48); coeffModulus.Set("FFFFFFFFC001"); parms.SetCoeffModulus(coeffModulus); var plainModulus = new BigUInt(7); plainModulus.Set(1 << 6); parms.SetPlainModulus(plainModulus); var polyModulus = new BigPoly(65, 1); polyModulus[0].Set(1); polyModulus[64].Set(1); parms.SetPolyModulus(polyModulus); parms.Validate(); var keygen = new KeyGenerator(parms, MemoryPoolHandle.AcquireNew()); keygen.Generate(); var encryptor = new Encryptor(parms, keygen.PublicKey, MemoryPoolHandle.AcquireNew()); var evaluator = new Evaluator(parms, MemoryPoolHandle.AcquireNew()); var decryptor = new Decryptor(parms, keygen.SecretKey, MemoryPoolHandle.AcquireNew()); var plain = new BigPoly(65, 1); var cipher = new BigPolyArray(2, 65, 1); plain.Set("0"); encryptor.Encrypt(plain, cipher); evaluator.TransformToNTT(cipher); evaluator.TransformFromNTT(cipher); decryptor.Decrypt(cipher, plain); Assert.IsTrue(plain.ToString() == "0"); plain.Set("1"); encryptor.Encrypt(plain, cipher); evaluator.TransformToNTT(cipher); evaluator.TransformFromNTT(cipher); decryptor.Decrypt(cipher, plain); Assert.IsTrue(plain.ToString() == "1"); plain.Set("Fx^10 + Ex^9 + Dx^8 + Cx^7 + Bx^6 + Ax^5 + 1x^4 + 2x^3 + 3x^2 + 4x^1 + 5"); encryptor.Encrypt(plain, cipher); evaluator.TransformToNTT(cipher); evaluator.TransformFromNTT(cipher); decryptor.Decrypt(cipher, plain); Assert.IsTrue(plain.ToString() == "Fx^10 + Ex^9 + Dx^8 + Cx^7 + Bx^6 + Ax^5 + 1x^4 + 2x^3 + 3x^2 + 4x^1 + 5"); }
public void EncryptAddDecryptNET() { var parms = new EncryptionParameters { DecompositionBitCount = 4, NoiseStandardDeviation = 3.19, NoiseMaxDeviation = 35.06 }; var coeffModulus = parms.CoeffModulus; coeffModulus.Resize(48); coeffModulus.Set("FFFFFFFFC001"); var plainModulus = parms.PlainModulus; plainModulus.Resize(7); plainModulus.Set(1 << 6); var polyModulus = parms.PolyModulus; polyModulus.Resize(64, 1); polyModulus[0].Set(1); polyModulus[63].Set(1); var keygen = new KeyGenerator(parms); keygen.Generate(); var Encoder = new BinaryEncoder(parms.PlainModulus); var encryptor = new Encryptor(parms, keygen.PublicKey); var evaluator = new Evaluator(parms, keygen.EvaluationKeys); var decryptor = new Decryptor(parms, keygen.SecretKey); var encrypted1 = encryptor.Encrypt(Encoder.Encode(0x12345678)); var encrypted2 = encryptor.Encrypt(Encoder.Encode(0x54321)); var sum = evaluator.Add(encrypted1, encrypted2); Assert.AreEqual(0x12399999UL, Encoder.DecodeUInt64(decryptor.Decrypt(sum))); encrypted1 = encryptor.Encrypt(Encoder.Encode(0)); encrypted2 = encryptor.Encrypt(Encoder.Encode(0)); sum = evaluator.Add(encrypted1, encrypted2); Assert.AreEqual(0UL, Encoder.DecodeUInt64(decryptor.Decrypt(sum))); encrypted1 = encryptor.Encrypt(Encoder.Encode(0)); encrypted2 = encryptor.Encrypt(Encoder.Encode(5)); sum = evaluator.Add(encrypted1, encrypted2); Assert.AreEqual(5UL, Encoder.DecodeUInt64(decryptor.Decrypt(sum))); encrypted1 = encryptor.Encrypt(Encoder.Encode(5)); encrypted2 = encryptor.Encrypt(Encoder.Encode(-3)); sum = evaluator.Add(encrypted1, encrypted2); Assert.AreEqual(2, Encoder.DecodeInt32(decryptor.Decrypt(sum))); encrypted1 = encryptor.Encrypt(Encoder.Encode(-7)); encrypted2 = encryptor.Encrypt(Encoder.Encode(2)); sum = evaluator.Add(encrypted1, encrypted2); Assert.AreEqual(-5, Encoder.DecodeInt32(decryptor.Decrypt(sum))); }
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 void FVEncryptSquareDecryptNET() { var parms = new EncryptionParameters(MemoryPoolHandle.AcquireNew()); parms.SetDecompositionBitCount(4); parms.SetNoiseStandardDeviation(3.19); parms.SetNoiseMaxDeviation(35.06); var coeffModulus = new BigUInt(48); coeffModulus.Set("FFFFFFFFC001"); parms.SetCoeffModulus(coeffModulus); var plainModulus = new BigUInt(7); plainModulus.Set(1 << 6); parms.SetPlainModulus(plainModulus); var polyModulus = new BigPoly(65, 1); polyModulus[0].Set(1); polyModulus[64].Set(1); parms.SetPolyModulus(polyModulus); parms.Validate(); var keygen = new KeyGenerator(parms, MemoryPoolHandle.AcquireNew()); keygen.Generate(); var encoder = new BalancedEncoder(parms.PlainModulus, MemoryPoolHandle.AcquireNew()); var encryptor = new Encryptor(parms, keygen.PublicKey, MemoryPoolHandle.AcquireNew()); var evaluator = new Evaluator(parms, MemoryPoolHandle.AcquireNew()); var decryptor = new Decryptor(parms, keygen.SecretKey, MemoryPoolHandle.AcquireNew()); var encrypted1 = encryptor.Encrypt(encoder.Encode(1)); var product = evaluator.Square(encrypted1); Assert.AreEqual(1UL, encoder.DecodeUInt64(decryptor.Decrypt(product))); encrypted1 = encryptor.Encrypt(encoder.Encode(0)); product = evaluator.Square(encrypted1); Assert.AreEqual(0UL, encoder.DecodeUInt64(decryptor.Decrypt(product))); encrypted1 = encryptor.Encrypt(encoder.Encode(-5)); product = evaluator.Square(encrypted1); Assert.AreEqual(25UL, encoder.DecodeUInt64(decryptor.Decrypt(product))); encrypted1 = encryptor.Encrypt(encoder.Encode(-1)); product = evaluator.Square(encrypted1); Assert.AreEqual(1UL, encoder.DecodeUInt64(decryptor.Decrypt(product))); encrypted1 = encryptor.Encrypt(encoder.Encode(123)); product = evaluator.Square(encrypted1); Assert.AreEqual(15129UL, encoder.DecodeUInt64(decryptor.Decrypt(product))); }
public static ConfigFileVO ReadConfigFileByEditModel(string filePath, string editPassword, out string errorInfo) { FileStream fs = null; BinaryReader binReader = null; ConfigFileVO vo = new ConfigFileVO(); vo.IsOnlyView = false; vo.ConfigFilePath = filePath; try { fs = new FileStream(filePath, FileMode.Open); binReader = new BinaryReader(fs, Encoding.Default); int totalLength = (int)fs.Length; int encryptedViewPasswordByteArrayLength = binReader.ReadInt32(); byte[] encryptedViewPasswordByteArray = binReader.ReadBytes(encryptedViewPasswordByteArrayLength); byte[] viewPasswordByteArray = _Decryptor.Decrypt(encryptedViewPasswordByteArray, editPassword); string viewPasswordStr = Encoding.Default.GetString(viewPasswordByteArray); if (viewPasswordStr.StartsWith(VIEW_PASSWORD_PREFIX) == false) { errorInfo = "解密失败,请确认是否输入了正确的用于编辑配置的管理员密码"; return(null); } else { vo.EditPassword = editPassword; vo.ViewPassword = viewPasswordStr.Substring(VIEW_PASSWORD_PREFIX.Length); } byte[] encryptedConfigByteArray = binReader.ReadBytes(totalLength - 4 - encryptedViewPasswordByteArrayLength); byte[] configByteArray = _Decryptor.Decrypt(encryptedConfigByteArray, vo.ViewPassword); string configStr = Encoding.Default.GetString(configByteArray); vo.AllConfigs = JsonMapper.ToObject <List <OneConfigJsonVO> >(configStr); errorInfo = null; return(vo); } catch { errorInfo = "解密失败,请确认是否输入了正确的用于编辑配置的管理员密码"; return(null); } finally { if (binReader != null) { binReader.Close(); } if (fs != null) { fs.Close(); } } }
public void FVEncryptAddsNoiseNET() { var parms = new EncryptionParameters(MemoryPoolHandle.AcquireNew()); parms.SetDecompositionBitCount(4); parms.SetNoiseStandardDeviation(3.19); parms.SetNoiseMaxDeviation(35.06); var coeffModulus = new BigUInt(48); coeffModulus.Set("FFFFFFFFC001"); parms.SetCoeffModulus(coeffModulus); var plainModulus = new BigUInt(7); plainModulus.Set(1 << 6); parms.SetPlainModulus(plainModulus); var polyModulus = new BigPoly(65, 1); polyModulus[0].Set(1); polyModulus[64].Set(1); parms.SetPolyModulus(polyModulus); parms.Validate(); var Encoder = new BinaryEncoder(parms.PlainModulus, MemoryPoolHandle.AcquireNew()); var keygen = new KeyGenerator(parms, MemoryPoolHandle.AcquireNew()); keygen.Generate(); var encryptor = new Encryptor(parms, keygen.PublicKey, MemoryPoolHandle.AcquireNew()); // however, this line is fine Assert.AreEqual(encryptor.PublicKey[0], keygen.PublicKey[0]); Assert.AreEqual(encryptor.PublicKey[1], keygen.PublicKey[1]); var encrypted1 = encryptor.Encrypt(Encoder.Encode(0x12345678)); var encrypted2 = encryptor.Encrypt(Encoder.Encode(0x12345678)); // this is what we want to check Assert.AreNotEqual(encrypted1[0], encrypted2[0]); Assert.AreNotEqual(encrypted1[1], encrypted2[1]); var decryptor = new Decryptor(parms, keygen.SecretKey, MemoryPoolHandle.AcquireNew()); Assert.AreEqual(0x12345678U, Encoder.DecodeUInt32(decryptor.Decrypt(encrypted1))); Assert.AreEqual(0x12345678U, Encoder.DecodeUInt32(decryptor.Decrypt(encrypted2))); }
public void Create2Test() { SEALContext context = GlobalContext.BFVContext; KeyGenerator keygen1 = new KeyGenerator(context); Encryptor encryptor1 = new Encryptor(context, keygen1.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); Encryptor encryptor2 = new Encryptor(context, keygen2.PublicKey); Decryptor decryptor2 = new Decryptor(context, keygen2.SecretKey); Plaintext plain3 = new Plaintext(); decryptor2.Decrypt(cipher, plain3); Assert.AreNotSame(plain, plain3); Assert.AreEqual(plain, plain3); KeyGenerator keygen3 = new KeyGenerator(context, keygen1.SecretKey, keygen1.PublicKey); Encryptor encryptor3 = new Encryptor(context, keygen3.PublicKey); Decryptor decryptor3 = new Decryptor(context, keygen3.SecretKey); Plaintext plain4 = new Plaintext(); decryptor3.Decrypt(cipher, plain4); Assert.AreNotSame(plain, plain4); Assert.AreEqual(plain, plain4); Ciphertext cipher2 = new Ciphertext(); plain2.Release(); encryptor3.Encrypt(plain, cipher2); decryptor2.Decrypt(cipher2, plain2); Assert.AreNotSame(plain, plain2); Assert.AreEqual(plain, plain2); }
public void FVEncryptExponentiateDecryptNET() { var parms = new EncryptionParameters(MemoryPoolHandle.AcquireNew()); parms.SetDecompositionBitCount(4); parms.SetNoiseStandardDeviation(3.19); parms.SetNoiseMaxDeviation(35.06); var coeffModulus = new BigUInt(48); coeffModulus.Set("FFFFFFFFC001"); parms.SetCoeffModulus(coeffModulus); var plainModulus = new BigUInt(7); plainModulus.Set(1 << 6); parms.SetPlainModulus(plainModulus); var polyModulus = new BigPoly(65, 1); polyModulus[0].Set(1); polyModulus[64].Set(1); parms.SetPolyModulus(polyModulus); parms.Validate(); var keygen = new KeyGenerator(parms, MemoryPoolHandle.AcquireNew()); keygen.Generate(1); var encoder = new BinaryEncoder(parms.PlainModulus, MemoryPoolHandle.AcquireNew()); var encryptor = new Encryptor(parms, keygen.PublicKey, MemoryPoolHandle.AcquireNew()); var evaluator = new Evaluator(parms, keygen.EvaluationKeys, MemoryPoolHandle.AcquireNew()); var decryptor = new Decryptor(parms, keygen.SecretKey, MemoryPoolHandle.AcquireNew()); var encrypted = encryptor.Encrypt(encoder.Encode(5)); var power = evaluator.Exponentiate(encrypted, 1); Assert.AreEqual(5, encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(encoder.Encode(7)); power = evaluator.Exponentiate(encrypted, 2); Assert.AreEqual(49, encoder.DecodeInt32(decryptor.Decrypt(power))); encrypted = encryptor.Encrypt(encoder.Encode(-7)); power = evaluator.Exponentiate(encrypted, 3); Assert.AreEqual(-343, encoder.DecodeInt32(decryptor.Decrypt(power))); }
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()); } }
internal void ConfirmPetSharingRequest(string token) { logger.Trace("Recived Confirm Pet share request"); try { if (String.IsNullOrEmpty(token)) { logger.Error("Recived Confirm Pet share request token is empty"); throw new CustomException("Recived Confirm Pet share request token is empty", (int)ErrorCode.VALIDATIONFAILED); } var userId = Decryptor.Decrypt(token).Split('|')[0]; var petId = Decryptor.Decrypt(token).Split('|')[1]; var sharedUserId = Decryptor.Decrypt(token).Split('|')[2]; if (String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(petId) || String.IsNullOrEmpty(sharedUserId)) { logger.Error("Recived Confirm Pet share request some of the properties empty"); throw new CustomException("Recived Confirm Pet share request some of the properties empty", (int)ErrorCode.VALIDATIONFAILED); } int iUserId = int.Parse(userId); Int64 ipetId = Int64.Parse(petId); int isharedUserId = int.Parse(sharedUserId); using (var ctx = new PetWhizzEntities()) { petOwner PetOwner = ctx.petOwners.Where(a => a.userId == iUserId && a.petId == ipetId && a.sharedUserId == isharedUserId).FirstOrDefault(); if (PetOwner == null) { logger.Error("No Owner request found for userId -" + userId + " & petId -" + petId + " by userId- " + sharedUserId); throw new CustomException("Recived Confirm Pet share request some of the properties empty", (int)ErrorCode.NORECORDFOUND); } ctx.petOwners.Attach(PetOwner); PetOwner.isActive = true; PetOwner.acceptedTime = DateTime.Now; PetOwner.isMainOwner = false; ctx.SaveChanges(); logger.Trace("Confirm Pet share request completed successfully"); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="GeneralSecurityException"/> public virtual KeyProvider.KeyVersion DecryptEncryptedKey(KeyProviderCryptoExtension.EncryptedKeyVersion encryptedKeyVersion) { // Fetch the encryption key material string encryptionKeyVersionName = encryptedKeyVersion.GetEncryptionKeyVersionName (); KeyProvider.KeyVersion encryptionKey = keyProvider.GetKeyVersion(encryptionKeyVersionName ); Preconditions.CheckNotNull(encryptionKey, "KeyVersion name '%s' does not exist", encryptionKeyVersionName); Preconditions.CheckArgument(encryptedKeyVersion.GetEncryptedKeyVersion().GetVersionName ().Equals(KeyProviderCryptoExtension.Eek), "encryptedKey version name must be '%s', is '%s'" , KeyProviderCryptoExtension.Eek, encryptedKeyVersion.GetEncryptedKeyVersion().GetVersionName ()); // Encryption key IV is determined from encrypted key's IV byte[] encryptionIV = KeyProviderCryptoExtension.EncryptedKeyVersion.DeriveIV(encryptedKeyVersion .GetEncryptedKeyIv()); CryptoCodec cc = CryptoCodec.GetInstance(keyProvider.GetConf()); Decryptor decryptor = cc.CreateDecryptor(); decryptor.Init(encryptionKey.GetMaterial(), encryptionIV); KeyProvider.KeyVersion encryptedKV = encryptedKeyVersion.GetEncryptedKeyVersion(); int keyLen = encryptedKV.GetMaterial().Length; ByteBuffer bbIn = ByteBuffer.AllocateDirect(keyLen); ByteBuffer bbOut = ByteBuffer.AllocateDirect(keyLen); bbIn.Put(encryptedKV.GetMaterial()); bbIn.Flip(); decryptor.Decrypt(bbIn, bbOut); bbOut.Flip(); byte[] decryptedKey = new byte[keyLen]; bbOut.Get(decryptedKey); return(new KeyProvider.KeyVersion(encryptionKey.GetName(), Ek, decryptedKey)); }
private void testDecryptingWithBadPasswordFails() { Decryptor cryptor = new Decryptor(); string decrypted = cryptor.Decrypt(TestStrings.IOS_ENCRYPTED_V2_NON_BLOCK_INTERVAL, "bad-password"); this.reportSuccess(MethodBase.GetCurrentMethod().Name, decrypted == ""); }
static public List <List <long> > decryptValues(List <List <Ciphertext> > weihtedSums, SecretKey sk, SEALContext context) { List <List <long> > results = new List <List <long> >(); Decryptor decryptor = new Decryptor(context, sk); IntegerEncoder encoder = new IntegerEncoder(context); int sample_ind = 0; foreach (List <Ciphertext> sample in weihtedSums) { List <long> resultsRow = new List <long>(); foreach (Ciphertext encryptedClassScore in sample) { Plaintext plainClassScore = new Plaintext(); if (decryptor.InvariantNoiseBudget(encryptedClassScore) == 0) { throw new Exception("Noise budget depleated in sample " + sample_ind + ". Aborting..."); } decryptor.Decrypt(encryptedClassScore, plainClassScore); long ClassScore = encoder.DecodeInt64(plainClassScore) / (1000 * 1000); resultsRow.Add(ClassScore); } results.Add(resultsRow); sample_ind++; } return(results); }
private bool Authorize(HttpActionContext actionContext) { try { string encryptedAuthHeader = ""; IEnumerable <string> headers; if (actionContext.ControllerContext.Request.Headers.TryGetValues("Authorization", out headers)) { encryptedAuthHeader = headers.FirstOrDefault(); if (string.IsNullOrEmpty(encryptedAuthHeader)) { throw new Exception("Unauthorized Call"); } string decryptedHeader = Decryptor.Decrypt(encryptedAuthHeader).Split('|')[1]; if (!ValidateAuthToken(decryptedHeader)) { throw new CustomException("Token Expired", (int)ErrorCode.TOKENEXPIRED); } } else { throw new Exception("Unauthorized Call"); } return(true); } catch (CustomException) { throw; } catch (Exception) { return(false); } }
public void Decrypt_EncyptedByteArrayFromFCMService_ShouldSuccessfullyDecrypt() { // use this captured data for debugging ////// generated on the client - ECDH with curve prime256v1////// // random bytes var authSecret = new byte[] { 5, 47, 48, 155, 244, 31, 204, 235, 11, 247, 67, 120, 24, 137, 25, 153 }; //// public key sent to the server var receiverPublicKeyBytes = new byte[] { 4, 234, 243, 178, 1, 91, 224, 122, 211, 185, 63, 90, 135, 90, 206, 224, 43, 63, 63, 131, 227, 22, 157, 108, 31, 176, 83, 27, 70, 246, 89, 112, 7, 102, 79, 42, 205, 17, 100, 100, 149, 198, 135, 95, 241, 189, 182, 61, 103, 161, 4, 244, 127, 185, 128, 18, 139, 78, 3, 169, 111, 218, 80, 73, 55 }; //// private key kept on the client var privateKey = new byte[] { 250, 117, 42, 156, 20, 153, 20, 193, 233, 136, 185, 246, 56, 52, 250, 150, 120, 250, 72, 147, 182, 144, 120, 103, 76, 11, 175, 143, 92, 1, 177, 59 }; //// received from the server var salt = new byte[] { 248, 70, 134, 75, 160, 188, 58, 83, 105, 238, 59, 171, 27, 115, 224, 200 }; //// server public key var senderPublicKeyBytes = new byte[] { 4, 26, 9, 166, 16, 222, 177, 154, 230, 15, 231, 11, 89, 108, 66, 97, 247, 3, 158, 199, 93, 98, 187, 162, 175, 76, 127, 2, 149, 67, 13, 195, 26, 145, 46, 223, 4, 34, 46, 70, 57, 0, 98, 139, 79, 25, 84, 187, 176, 126, 50, 108, 192, 61, 207, 83, 248, 189, 14, 10, 182, 18, 141, 52, 92 }; //// actual data that needs decoding var rawData = new byte[] { 127, 5, 92, 210, 222, 94, 48, 180, 122, 71, 186, 120, 91, 171, 10, 6, 14, 182, 145, 108, 136, 161, 172, 8, 67, 27, 136, 55, 6, 224, 180, 181, 141, 242, 21, 101, 235, 6, 125, 162, 97, 236, 49, 150, 61, 225, 130, 58, 57, 93, 37, 79, 208, 21, 8, 139, 72, 235, 12, 173, 50 }; var decryptor = new Decryptor(privateKey, receiverPublicKeyBytes, authSecret); var decryptedBytes = decryptor.Decrypt(rawData, senderPublicKeyBytes, salt); var result = Encoding.UTF8.GetString(decryptedBytes); Assert.AreEqual("{\"from\":\"550920961559\",\"priority\":\"normal\"}", result); }
public ActionResult Register(User user) { if (ModelState.IsValid) { var encrypt = Encryptor.Encrypt(user.Password); user.Password = encrypt; var db = new UserDAO(); var dao = db.Create(user); if (dao == 1) { //nếu đăng kí thành công thì sẽ tự động đăg nhập TempData["Success"] = "Thêm tài khoản thành công"; Login(user.Username, Decryptor.Decrypt(user.Password)); //gọi hàm login return(RedirectToAction("Index", "Home")); } else if (dao == 0) { TempData["Error"] = "Email này đã tồn tại"; return(View()); } else if (dao == -1) { TempData["Error"] = "Tài khoản này đã tồn tại"; return(View("Register")); } else { ModelState.AddModelError("", "Thêm tài khoản thất bại"); } } return(View()); }
static void Main(string[] args) { var str = Encryptor.Encrypt("qwerty"); Console.WriteLine(str); Console.WriteLine(Decryptor.Decrypt("BmwzQACRCmddGbSXdUJIGw==")); }
public void DecryptsToOriginalPlainText() { byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least."); byte[] decryptedBytes; using (SymmetricAlgorithm algorithm = new AesManaged()) { byte[] wrongDecryptionKey = algorithm.Key; algorithm.GenerateKey(); byte[] encryptionKey = algorithm.Key; Assert.AreNotEqual(encryptionKey, wrongDecryptionKey); byte[] ciphertextBytes, iv; using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv)) { Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key); Assert.AreEqual(iv, encryptor.Algorithm.IV); ciphertextBytes = encryptor.Encrypt(plaintextBytes); } using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions)) { Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key); Assert.AreEqual(iv, decryptor.Algorithm.IV); decryptedBytes = decryptor.Decrypt(ciphertextBytes); } } Assert.AreEqual(plaintextBytes, decryptedBytes); }
private void performDecryptionTest(string functionName, string encrypted, string expected, string password) { Decryptor cryptor = new Decryptor(); string decrypted = cryptor.Decrypt(encrypted, password); this.reportSuccess(functionName, decrypted == expected); }
public static string Decrypt(string Parameter) { Decryptor Decry = new Decryptor(EncryptionAlgorithm.TripleDes); Decry.IV = Encoding.ASCII.GetBytes("t3ilc0m3"); return(Decry.Decrypt(Parameter, "3wmotherwdrtybnio12ewq23")); }
/// <summary> /// Decrypts a string. /// </summary> /// <param name="Text">The encrypted string to be decrypted.</param> /// <param name="Key">The 8-bit string for decryption.</param> /// <returns>The plain text.</returns> public string Decrypt(string Text, string Key) { if(Key.Length != 8) throw new Exception("Key must be a 8-bit string!"); byte[] IV = null; byte[] cipherText = null; byte[] key = null; byte[] plainText = null; try { Decryptor dec = new Decryptor(EncryptionAlgorithm.Des); IV = Encoding.ASCII.GetBytes("init vec"); // "init vec is big." dec.IV = IV; key = Encoding.ASCII.GetBytes(Key); cipherText = Convert.FromBase64String(Text); plainText = dec.Decrypt(cipherText, key); } catch(Exception ex) { throw new Exception("Exception while decrypting. " + ex.Message); } return Encoding.ASCII.GetString(plainText); }
public ActionResult Register(User user) { var pass = Encryptor.Encrypt(user.Password); user.Password = pass; var db = new UserDAO(); var kq = db.CreateUSer(user); if (kq == 1) { //dang ki thanh cong TempData["Success"] = "Thêm tài khoản thành công"; Login(user.Username, Decryptor.Decrypt(user.Password)); return(RedirectToAction("Index", "Home")); } else if (kq == 0) { TempData["Error"] = "Email đã được đăng kí"; } else if (kq == -1) { TempData["Error"] = "Tài khoản đã tồn tại"; } else { ModelState.AddModelError("", "Thêm tài khoản thất bại"); } return(View()); }
public ActionResult ChangePassword(UserModel userModel) { UserDAO db = new UserDAO(); if (ModelState.IsValid) { var user = db.GetUserString(userModel.Username); if (user != null) { if (Decryptor.Decrypt(user.Password) == userModel.Password) //nếu đúng pass của tài khoản mới cập nhập { db.UpdatePass(user.Email, Encryptor.Encrypt(userModel.NewPassword)); //Hàm cập nhập mật khẩu TempData["Success"] = "Đổi mật khẩu thành công"; return(RedirectToAction("Index", "Home")); } else { TempData["Error"] = "Mật khẩu cũ không tồn tại"; return(View()); } } } TempData["Error"] = "Đổi mật khẩu thất bại"; return(View()); }
// 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}"); }
internal static byte[] DecryptByKey(byte[] encryptedPassword, byte[] initializationVector, byte[] passwordKey) { var dec = new Decryptor(ENCRYPTION_ALGORITHM); dec.IV = initializationVector; return(dec.Decrypt(encryptedPassword, passwordKey)); }
public void FVEncryptAddsNoiseNET() { var parms = new EncryptionParameters { DecompositionBitCount = 4, NoiseStandardDeviation = 3.19, NoiseMaxDeviation = 35.06 }; var coeffModulus = parms.CoeffModulus; coeffModulus.Resize(48); coeffModulus.Set("FFFFFFFFC001"); var plainModulus = parms.PlainModulus; plainModulus.Resize(7); plainModulus.Set(1 << 6); var polyModulus = parms.PolyModulus; polyModulus.Resize(64, 1); polyModulus[0].Set(1); polyModulus[63].Set(1); var Encoder = new BinaryEncoder(parms.PlainModulus); var keygen = new KeyGenerator(parms); keygen.Generate(); var encryptor = new Encryptor(parms, keygen.PublicKey); // however, this line is fine Assert.AreEqual(encryptor.PublicKey[0], keygen.PublicKey[0]); Assert.AreEqual(encryptor.PublicKey[1], keygen.PublicKey[1]); var encrypted1 = encryptor.Encrypt(Encoder.Encode(0x12345678)); var encrypted2 = encryptor.Encrypt(Encoder.Encode(0x12345678)); // this is what we want to check Assert.AreNotEqual(encrypted1[0], encrypted2[0]); Assert.AreNotEqual(encrypted1[1], encrypted2[1]); var decryptor = new Decryptor(parms, keygen.SecretKey); Assert.AreEqual(0x12345678U, Encoder.DecodeUInt32(decryptor.Decrypt(encrypted1))); Assert.AreEqual(0x12345678U, Encoder.DecodeUInt32(decryptor.Decrypt(encrypted2))); }
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(); }
/// <summary> /// Perform a matrix operation by invocating an Azure Function /// </summary> /// <param name="sid">Session ID</param> /// <param name="operation">Operation to perform</param> /// <param name="code">Azure Key needed to execute Azure Function in Azure</param> /// <param name="ciphera">Ciphertext containing a codified matrix</param> /// <param name="cipherb">Ciphertext containing a second codified matrix</param> /// <returns>Plaintext with the result of the operation</returns> private async Task <Plaintext> PerformOperation(string sid, string operation, string code, Plaintext plaina, Plaintext plainb) { string b64a = Utilities.EncryptToBase64(plaina, encryptor_); string b64b = Utilities.EncryptToBase64(plainb, encryptor_); string json = $"{{ \"sid\": \"{sid}\", \"matrixa\": \"{b64a}\", \"matrixb\": \"{b64b}\" }}"; double kbs = (b64a.Length + b64b.Length) / 1024.0; Log($"Matrix A:\n{b64a}"); Log($"Matrix B:\n{b64b}"); Log($"Sending {kbs} KB of ciphertext data to Azure Function"); Uri function = GetUri(operation, code); HttpContent content = new StringContent(json, Encoding.UTF8); HttpResponseMessage response; try { response = await httpClient_.PostAsync(function, content); } catch (HttpRequestException ex) { Log($"Exception during request: {ex.ToString()}"); return(null); } if (!response.IsSuccessStatusCode) { Log($"Function call failed with status code: {response.StatusCode}"); return(null); } string responseStr = await response.Content.ReadAsStringAsync(); dynamic deserialized = JsonConvert.DeserializeObject(responseStr); string resultb64 = deserialized?.result; Log($"Result:\n{resultb64}"); Ciphertext result = Utilities.Base64ToCiphertext(resultb64, GlobalProperties.Context); Plaintext plain = new Plaintext(); Log("Noise budget: " + decryptor_.InvariantNoiseBudget(result) + " bits"); decryptor_.Decrypt(result, plain); return(plain); }
public string Decrypt(string inText) { Decryptor decryptor = new Decryptor(privateKeyRing, passphrase); string outText = decryptor.Decrypt(inText); //Console.WriteLine("Decryption done."); return(outText); }
public void CausesDecryptionToReturnNonsense() { byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test!"); byte[] decryptedBytes, decryptedBytesFromWrongKey = null; using (SymmetricAlgorithm algorithm = new AesManaged()) { byte[] wrongDecryptionKey = algorithm.Key; algorithm.GenerateKey(); byte[] encryptionKey = algorithm.Key; Assert.AreNotEqual(encryptionKey, wrongDecryptionKey); byte[] ciphertextBytes, iv; using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv)) { Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key); Assert.AreEqual(iv, encryptor.Algorithm.IV); ciphertextBytes = encryptor.Encrypt(plaintextBytes); } using (Decryptor decryptorWithWrongKey = new Decryptor(algorithm, wrongDecryptionKey, iv, Encryption.DefaultOptions)) { Assert.AreEqual(wrongDecryptionKey, decryptorWithWrongKey.Algorithm.Key); Assert.AreEqual(iv, decryptorWithWrongKey.Algorithm.IV); try { decryptedBytesFromWrongKey = decryptorWithWrongKey.Decrypt(ciphertextBytes); } catch (CryptographicException e) { // "Padding is invalid and cannot be removed." Assert.IsNull(decryptedBytesFromWrongKey); Console.WriteLine(e.Message); } } using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions)) { Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key); Assert.AreEqual(iv, decryptor.Algorithm.IV); decryptedBytes = decryptor.Decrypt(ciphertextBytes); } } Assert.AreNotEqual(decryptedBytes, decryptedBytesFromWrongKey); Assert.AreEqual(plaintextBytes, decryptedBytes); }
private void performSymmetricTest(string functionName, string plaintext, string password) { Encryptor encryptor = new Encryptor(); string encryptedB64 = encryptor.Encrypt(plaintext, password); Decryptor decryptor = new Decryptor(); string decrypted = decryptor.Decrypt(encryptedB64, password); this.reportSuccess(functionName, decrypted == plaintext); }
private void performSymmetricTestWithExplicitSchema(string functionName, string plaintext, string password, Schema schemaVersion) { Encryptor encryptor = new Encryptor(); string encryptedB64 = encryptor.Encrypt(plaintext, password, schemaVersion); Decryptor decryptor = new Decryptor(); string decrypted = decryptor.Decrypt(encryptedB64, password); this.reportSuccess(functionName, decrypted == plaintext); }
private void testCannotUseWithUnsupportedSchemaVersions() { Encryptor encryptor = new Encryptor(); string encryptedB64 = encryptor.Encrypt(TestStrings.SAMPLE_PLAINTEXT, TestStrings.SAMPLE_PASSWORD_A); byte[] encrypted = Convert.FromBase64String(encryptedB64); encrypted[0] = 0x03; string encryptedV3 = Convert.ToBase64String(encrypted); Decryptor decryptor = new Decryptor(); string decrypted = decryptor.Decrypt(encryptedV3, TestStrings.SAMPLE_PASSWORD_A); this.reportSuccess(MethodBase.GetCurrentMethod().Name, decrypted == ""); }