Inheritance: MonoBehaviour
            public void Before_each_test()
            {
                asymmetricEncryptionProvider = new AsymmetricEncryptionProvider();
                symmetricEncryptionProvider = new SymmetricEncryptionProvider();
                hashingProvider = new HashingProvider();

                smallKeyGenerator = new KeyGenerator(symmetricEncryptionProvider, asymmetricEncryptionProvider, hashingProvider);

                license = new ClientLicense();
                generationOptions = new LicenseGenerationOptions();

                license.UniqueId = Guid.NewGuid();
                license.Product = new Product();
                license.Product.Name = "My Great Uber Cool Product, with new juice!";
                license.Product.ProductId = 1;

                license.LicenseSets = new NotifyList<LicenseSet>();
                license.LicenseSets.Add(new LicenseSet());

                license.LicenseSets.First().SupportedLicenseTypes = LicenseKeyTypeFlag.SingleUser;
                license.LicenseSets.First().SupportedLicenseTypes |= LicenseKeyTypeFlag.Enterprise;
                license.LicenseSets.First().SupportedLicenseTypes |= LicenseKeyTypeFlag.Unlimited;

                generationOptions.LicenseKeyType = LicenseKeyTypes.Enterprise;

                string productHash = hashingProvider.Checksum32(license.GetLicenseProductIdentifier()).ToString("X");

                placeholders = smallKeyGenerator.CreateLicensePlaceholders(license, generationOptions);
                placeholdersInTemplate = KeyGenerator.FindAllPlaceholdersInTemplate(KeyGenerator.licenseKeyTemplate, placeholders);

                key = smallKeyGenerator.GenerateLicenseKey("TEST", license, generationOptions);
            }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a temporary CipherKey on disk, extracts and compares the copy
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void KeyFactoryTest()
        {
            string path = GetTempPath();
            KeyParams key1;
            KeyParams key2;
            CipherKey cikey;
            CipherDescription desc;

            using (KeyFactory factory = new KeyFactory(path))
            {
                // create a key/iv
                key1 = new KeyGenerator().GetKeyParams(32, 16, 64);

                // alt: manual creation
                /*kf.Create(
                    kp,
                    Engines.RDX,
                    32,
                    IVSizes.V128,
                    CipherModes.CTR,
                    PaddingModes.X923,
                    BlockSizes.B128,
                    RoundCounts.R14,
                    Digests.Keccak512,
                    64,
                    Digests.Keccak512);*/

                // cipher paramaters
                desc = new CipherDescription(
                    SymmetricEngines.RDX, 32,
                    IVSizes.V128,
                    CipherModes.CTR,
                    PaddingModes.X923,
                    BlockSizes.B128,
                    RoundCounts.R14,
                    Digests.Keccak512,
                    64,
                    Digests.Keccak512);

                // create the key
                factory.Create(desc, key1);
                // extract
                factory.Extract(out cikey, out key2);
            }

            if (!cikey.Description.Equals(desc))
                throw new Exception();
            // compare key material
            if (!Compare.AreEqual(key1.IKM, key2.IKM))
                throw new Exception();
            if (!Compare.AreEqual(key1.IV, key2.IV))
                throw new Exception();
            if (!Compare.AreEqual(key1.Key, key2.Key))
                throw new Exception();

            if (File.Exists(path))
                File.Delete(path);
        }
            public void Before_each_test()
            {
                clientLicenseRepoistory = new ClientLicenseRepository(objectSerializationProvider, symmetricEncryptionProvider);
                clientLicenseService = new ClientLicenseService(clientLicenseRepoistory);
                serviceProductsRepository = new ServiceProductsRepository(new ScutexServiceEntities());
                symmetricEncryptionProvider = new SymmetricEncryptionProvider();
                asymmetricEncryptionProvider = new AsymmetricEncryptionProvider();
                hashingProvider = new HashingProvider();
                objectSerializationProvider = new ObjectSerializationProvider();
                numberDataGenerator = new NumberDataGenerator();
                packingService = new PackingService(numberDataGenerator);
                commonRepository = new CommonRepository(new ScutexServiceEntities());
                clientRepository = new ClientRepository(new ScutexServiceEntities());
                keyGenerator = new KeyGenerator(symmetricEncryptionProvider, asymmetricEncryptionProvider, hashingProvider);
                masterService = new MasterService(commonRepository);
                activationLogRepository = new ActivationLogRepoistory(new ScutexServiceEntities());

                activationLogService = new ActivationLogService(activationLogRepository, hashingProvider);
                keyService = new KeyManagementService(clientRepository, licenseKeyService, activationLogService, hashingProvider, serviceProductsRepository);
                commonService = new CommonService();

                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                path = path.Replace("file:\\", "");

                var mockCommonService = new Mock<ICommonService>();
                mockCommonService.Setup(common => common.GetPath()).Returns(path + "\\Data\\Client\\");

                string masterServiceDataText;

                using (TextReader reader = new StreamReader(path + "\\Data\\MasterService.dat"))
                {
                    masterServiceDataText = reader.ReadToEnd().Trim();
                }

                masterServiceData = objectSerializationProvider.Deserialize<MasterServiceData>(masterServiceDataText);

                var mockCommonRepository = new Mock<ICommonRepository>();
                mockCommonRepository.Setup(repo => repo.GetMasterServiceData()).Returns(masterServiceData);

                keyPairService = new KeyPairService(mockCommonService.Object, mockCommonRepository.Object);
                controlService = new ControlService(symmetricEncryptionProvider, keyPairService, packingService, masterService, objectSerializationProvider, asymmetricEncryptionProvider);
                servicesRepository = new ServicesRepository(new ScutexEntities());
                serviceStatusProvider = new ServiceStatusProvider(symmetricEncryptionProvider, objectSerializationProvider, asymmetricEncryptionProvider);
                licenseActiviationProvider = new LicenseActiviationProvider(asymmetricEncryptionProvider, symmetricEncryptionProvider, objectSerializationProvider);
                servicesService = new ServicesService(servicesRepository, serviceStatusProvider, packingService, licenseActiviationProvider, null, null, null, null, null);
                licenseKeyService = new LicenseKeyService(keyGenerator, packingService, clientLicenseService);
                activationService = new ActivationService(controlService, keyService, keyPairService, objectSerializationProvider, asymmetricEncryptionProvider, null, null);

                string serviceData;

                using (TextReader reader = new StreamReader(path + "\\Data\\Service.dat"))
                {
                    serviceData = reader.ReadToEnd().Trim();
                }

                service = objectSerializationProvider.Deserialize<Service>(serviceData);
            }
Ejemplo n.º 4
0
 public byte[] Encrypt(byte[] blocks, short key)
 {
     var encryptedBlocks = new byte[blocks.Length];
     var keys = new KeyGenerator().GetKeys(key);
     for (var i = 0; i < blocks.Length; i++)
     {
         encryptedBlocks[i] = ProcessBlock(blocks[i], keys);
     }
     return encryptedBlocks;
 }
Ejemplo n.º 5
0
 public byte[] Decrypt(byte[] blocks, short key)
 {
     var decryptedBlocks = new byte[blocks.Length];
     var keys = new KeyGenerator().GetKeys(key).Reverse().ToArray();
     for (var i = 0; i < blocks.Length; i++)
     {
         decryptedBlocks[i] = ProcessBlock(blocks[i], keys);
     }
     return decryptedBlocks;
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Compress and encrypt a file, then decrypt and deflate to an output directory
        /// </summary>
        /// 
        /// <param name="InputDirectory">The path of the folder to be archived</param>
        /// <param name="OutputDirectory">The decompressed files output directory</param>
        /// <param name="CompressedFilePath">The name and path of the new compressed and encrypted archive</param>
        public static void CompressionCipherTest(string InputDirectory, string OutputDirectory, string CompressedFilePath)
        {
            KeyParams kp = new KeyGenerator().GetKeyParams(32, 16);
            // Create an archive //
            // create the cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for encryption
                cipher.Initialize(true, kp);

                // create the archive file
                using (FileStream fs = new FileStream(CompressedFilePath, FileMode.Create))
                {
                    // compress and encrypt directory
                    using (CompressionCipher cc = new CompressionCipher(true, cipher))
                    {
                        // set the input folder path and archive output stream
                        cc.Initialize(InputDirectory, fs);
                        // write the compressed and encrypted archive to file
                        cc.Write();
                    }
                }
            }

            // Inflate an archive //
            // create the cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for decryption
                cipher.Initialize(false, kp);

                // open the archive
                using (FileStream decmp = new FileStream(CompressedFilePath, FileMode.Open))
                {
                    // decrypt and inflate to output directory
                    using (CompressionCipher cc = new CompressionCipher(false, cipher))
                    {
                        // set the output folder path and archive path
                        cc.Initialize(OutputDirectory, decmp);
                        // decrypt and inflate the directory
                        cc.Write();
                    }
                }
            }
            // manual inspection of files..
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Create a unique string generator
            var keyGenerator = new KeyGenerator(20000000);

            // Derivate a minimum perfect hash function
            Console.WriteLine("Generating minimum perfect hash function for {0} keys", keyGenerator.NbKeys);
            var start = DateTime.Now;
            var hashFunction =  MPH.MinPerfectHash.Create(keyGenerator, 1);

            Console.WriteLine("Completed in {0:0.000000} s", DateTime.Now.Subtract(start).TotalMilliseconds / 1000.0);
            
            // Show the extra hash space necessary
            Console.WriteLine("Hash function map {0} keys to {1} hashes (load factor: {2:0.000000}%)",
                keyGenerator.NbKeys,hashFunction.N,
                ((keyGenerator.NbKeys * 100) / (double)hashFunction.N));

            // Check for any collision
            var used = new System.Collections.BitArray((int)hashFunction.N);
            keyGenerator.Rewind();
            start = DateTime.Now;
            for(var test = 0U; test<keyGenerator.NbKeys;test++ )
            {
                var hash = (int) hashFunction.Search(keyGenerator.Read());
                if(used[hash])
                {
                    Console.WriteLine("FAILED - Collision detected at {0}",test);
                    return;
                }
                used[hash] = true;
            }
            var end = DateTime.Now.Subtract(start).TotalMilliseconds;
            Console.WriteLine("PASS - No collision detected");

            Console.WriteLine("Total scan time : {0:0.000000} s",end/1000.0);
            Console.WriteLine("Average key hash time : {0} ms", end/(double)keyGenerator.NbKeys);
        }
Ejemplo n.º 8
0
 public zzGenericNode1(string string_0, Stream26 stream26_0)
 {
     base.Text           = KeyGenerator.GetFileName(string_0);
     stream26_0.Position = 28L;
     base.method_4(stream26_0);
 }
Ejemplo n.º 9
0
 public zzGenericNode1(string string_0, AbstractTreeNode1 class259_0)
 {
     base.Text = KeyGenerator.GetFileName(string_0);
     base.Nodes.Add(class259_0);
 }
Ejemplo n.º 10
0
        public void Test256BitKeyReturned()
        {
            string key = KeyGenerator.Generate256BitKey();

            Assert.NotNull(key);
        }
Ejemplo n.º 11
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Secure Iris");

            // Get Input from resource file or as args
            double[][] features;
            int        numberOfFeatures = 4;
            int        numOfRows        = 0;

            // Option to load from args and not the whole dataset that is stored in resources
            if (args.Length >= numberOfFeatures)
            {
                numOfRows = args.Length / numberOfFeatures;
                // Features:
                features = new double[numOfRows][];
                for (int i = 0; i < numOfRows; i++)
                {
                    features[i] = new double[numberOfFeatures];
                }
                for (int i = 0, l = args.Length; i < l; i++)
                {
                    features[i / numberOfFeatures][i % numberOfFeatures] = Double.Parse(args[i]);
                }
            }

            else  // load the whole dataset from resources
            {
                List <double[]> rows = new List <double[]>();

                var bytes = Properties.Resources.iris;
                numOfRows = 0;
                features  = SVCUtilities.SvcUtilities.LoadFeatures(bytes, numberOfFeatures, ref numOfRows);
            }
            Stopwatch clientStopwatch = new Stopwatch();

            clientStopwatch.Start();

            //svm algorithm parametrs calculated in python : training result
            double[][] vectors = new double[3][];
            vectors[0] = new[] { 4.5, 2.3, 1.3, 0.3 };
            vectors[1] = new[] { 5.1, 3.3, 1.7, 0.5 };
            vectors[2] = new[] { 5.1, 2.5, 3.0, 1.1 };

            double[][] coefficients = new double[1][];
            coefficients[0] = new double[] { -0.07724840262003278, -0.6705185831514366, 0.7477669857714694 };
            double[] intercepts = { 1.453766563649063 };


            // SEAL parameters client side
            Console.WriteLine("SecureSVC : ");

            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            ulong polyModulusDegree = 16384;
            int   power             = 40;

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

            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;



            var context = new SEALContext(parms);
            // Key generation
            KeyGenerator keygen    = new KeyGenerator(context);
            var          publicKey = keygen.PublicKey;
            var          secretKey = keygen.SecretKey;
            var          relinKeys = keygen.RelinKeys();

            var galoisKeys = keygen.GaloisKeys();
            var encryptor  = new Encryptor(context, publicKey);

            var decryptor = new Decryptor(context, secretKey);
            var encoder   = new CKKSEncoder(context);

            clientStopwatch.Stop();


            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(
                           $@"{OutputDir}IrisLinearSecured_{IsParallel}_{DateTime.Now.Day}_{DateTime.Now.ToShortTimeString().ToString().Replace(":", "_")}.txt")
                   )
            {
                // Only CONCEPT demonstation how to parrallel all the computation on all machine cpu's
                // Though the parallel here is done on the client side , in "real life" this parallel mechanism
                // Should on the server side
                if (IsParallel)
                {
                    int processorCount = Environment.ProcessorCount;
                    Console.WriteLine("Number Of Logical Processors: {0}", processorCount);

                    Svc[] machines = new Svc[processorCount];

                    Stopwatch[] innerProductStopwatchArr   = new Stopwatch[processorCount];
                    Stopwatch[] negateStopwatchArr         = new Stopwatch[processorCount];
                    Stopwatch[] degreeStopwatchArr         = new Stopwatch[processorCount];
                    Stopwatch[] serverDecisionStopWatchArr = new Stopwatch[processorCount];
                    Result[]    results = new Result[numOfRows];

                    Task[] tasks = new Task[processorCount];
                    for (int i = 0; i < processorCount; i++)
                    {
                        machines[i] = new Svc(vectors, coefficients, intercepts, "Linear", 0.25, 0.0, 3, 40, publicKey /*, secretKey*/, relinKeys, galoisKeys, 1, 4);
                        innerProductStopwatchArr[i]   = new Stopwatch();
                        negateStopwatchArr[i]         = new Stopwatch();
                        degreeStopwatchArr[i]         = new Stopwatch();
                        serverDecisionStopWatchArr[i] = new Stopwatch();
                    }
                    Stopwatch totalTime = new Stopwatch();
                    totalTime.Start();
                    for (int i = 0; i < numOfRows;)
                    {
                        for (int j = 0; j < processorCount && i < numOfRows; j++)
                        {
                            var secureSvc = machines[i % processorCount];
                            var feature   = features[i];
                            //Console.WriteLine($"\n\n $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                            List <object> l = new List <object>();
                            l.Add(secureSvc);                  //0
                            l.Add(feature);                    //1
                            l.Add(i);                          //2
                            l.Add(encoder);                    //3
                            l.Add(encryptor);                  //4
                            l.Add(decryptor);                  //5
                            l.Add(innerProductStopwatchArr[i % processorCount]);
                            l.Add(degreeStopwatchArr[i % processorCount]);
                            l.Add(negateStopwatchArr[i % processorCount]);
                            l.Add(serverDecisionStopWatchArr[i % processorCount]);

                            l.Add(results);
                            tasks[j] = new TaskFactory().StartNew(new Action <object>((test) =>
                            {
                                List <object> l2 = (List <object>)test;

                                SinglePredict((Svc)l2[0], (double[])l2[1], (int)l2[2], (CKKSEncoder)l2[3], (Encryptor)l2[4], (Decryptor)l2[5], (Stopwatch)l2[6], (Stopwatch)l2[7], (Stopwatch)l2[8], (Stopwatch)l2[9], scale, (Result[])l2[10]);
                            }), l);
                            i++;
                        }

                        await Task.WhenAll(tasks);
                    }

                    totalTime.Stop();

                    for (int i = 0; i < numOfRows; i++)
                    {
                        var result = results[i];
                        file.WriteLine($"{i} , {result.Estimation} , {result.TotalValue} ");
                    }

                    double innerProductTime = 0;
                    double degreeTime       = 0;
                    double negateTime       = 0;
                    double serverTime       = 0;

                    for (int i = 0; i < processorCount; i++)
                    {
                        innerProductTime = innerProductStopwatchArr[i].ElapsedMilliseconds;
                        degreeTime       = degreeStopwatchArr[i].ElapsedMilliseconds;
                        negateTime       = negateStopwatchArr[i].ElapsedMilliseconds;
                        serverTime       = serverDecisionStopWatchArr[i].ElapsedMilliseconds;
                    }
                    file.WriteLine($" Client time :  {clientStopwatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Total time for {numOfRows} samples :  {totalTime.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Avg time  :  {totalTime.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Inner Product time for  {numOfRows} samples :  {innerProductTime} ms  ");
                    file.WriteLine($" Inner Product Avg time  :  {innerProductTime * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Degree time for  {numOfRows} samples :  {degreeTime} ms  ");
                    file.WriteLine($" Degree Avg time  :  {degreeTime * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Negate time for  {numOfRows} samples :  {negateTime} ms  ");
                    file.WriteLine($" Negate Avg time  :  {negateTime * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Decision time for  {numOfRows} samples :  {serverTime} ms  ");
                    file.WriteLine($" Decision Avg time  :  {serverTime * 1000 / numOfRows} microSec ");
                }
                else
                {
                    //Initiate Stopwatch for performance measure
                    Stopwatch innerProductStopwatch   = new Stopwatch();
                    Stopwatch negateStopwatch         = new Stopwatch();
                    Stopwatch degreeStopwatch         = new Stopwatch();
                    Stopwatch serverDecisionStopWatch = new Stopwatch();

                    int featureSizeWithSpace = numberOfFeatures;

                    int batchSize = 200;
                    if (batchSize > 1)
                    {
                        featureSizeWithSpace = numberOfFeatures * 2;
                    }

                    Svc       clf       = new Svc(vectors, coefficients, intercepts, "Linear", 0.25, 0.0, 3, 40, publicKey /*, secretKey*/, relinKeys, galoisKeys, batchSize, featureSizeWithSpace);
                    Stopwatch totalTime = new Stopwatch();
                    totalTime.Start();
                    int start = 0;
                    //double[] batchFeatures = new double[batchSize * featureSizeWithSpace];
                    for (int i = 0; i < numOfRows;)
                    {
                        start = i;
                        double     finalResult = -10000;
                        double[][] batchRows   = new double[batchSize][];
                        for (int j = 0; j < batchSize && i < numOfRows; j++)
                        {
                            batchRows[j] = features[i];
                            i++;
                        }
                        double[] batchFeatures = GetBatchFeatures(batchRows, batchSize, numberOfFeatures, featureSizeWithSpace);


                        var plaintexts          = new Plaintext();
                        var featuresCiphertexts = new Ciphertext();
                        encoder.Encode(batchFeatures, scale, plaintexts);
                        encryptor.Encrypt(plaintexts, featuresCiphertexts);

                        //Server side start
                        var cypherResult = clf.Predict(featuresCiphertexts, true, true, innerProductStopwatch, degreeStopwatch, negateStopwatch, serverDecisionStopWatch);
                        // Server side end
                        Plaintext plainResult = new Plaintext();
                        decryptor.Decrypt(cypherResult, plainResult);
                        List <double> result = new List <double>();
                        encoder.Decode(plainResult, result);

                        for (int j = 0; j < batchSize && start < numOfRows; j++)
                        {
                            finalResult = result[j * featureSizeWithSpace];
                            int estimation = finalResult > 0 ? 0 : 1;
                            Console.WriteLine($"\n ************************************************");
                            Console.WriteLine($"SVC estimation{i} is : {estimation} , result : {finalResult}");
                            file.WriteLine($"{start} , {estimation} , {finalResult} ");
                            Console.WriteLine($"************************************************ \n");
                            start++;
                        }
                    }
                    totalTime.Stop();
                    file.WriteLine($" Client time :  {clientStopwatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Total time for {numOfRows} samples :  {totalTime.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Avg time  :  {totalTime.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Inner Product time for  {numOfRows} samples :  {innerProductStopwatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Inner Product Avg time  :  {innerProductStopwatch.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Degree time for  {numOfRows} samples :  {degreeStopwatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Degree Avg time  :  {degreeStopwatch.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Negate time for  {numOfRows} samples :  {negateStopwatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Negate Avg time  :  {negateStopwatch.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                    file.WriteLine($" Decision time for  {numOfRows} samples :  {serverDecisionStopWatch.ElapsedMilliseconds} ms  ");
                    file.WriteLine($" Decision Avg time  :  {serverDecisionStopWatch.ElapsedMilliseconds * 1000 / numOfRows} microSec ");
                }
            }
        }
        /// <summary>
        /// Proceeds the able async.
        /// </summary>
        /// <returns>The able async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next)
        {
            if (GetMethodAttributes(context.ServiceMethod).FirstOrDefault(x => typeof(EasyCachingAbleAttribute).IsAssignableFrom(x.GetType())) is EasyCachingAbleAttribute attribute)
            {
                var returnType = context.IsAsync()
                        ? context.ServiceMethod.ReturnType.GetGenericArguments().First()
                        : context.ServiceMethod.ReturnType;

                var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

                object cacheValue  = null;
                var    isAvailable = true;
                try
                {
                    if (attribute.IsHybridProvider)
                    {
                        cacheValue = await HybridCachingProvider.GetAsync(cacheKey, returnType);
                    }
                    else
                    {
                        var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                        cacheValue = await _cacheProvider.GetAsync(cacheKey, returnType);
                    }
                }
                catch (Exception ex)
                {
                    if (!attribute.IsHighAvailability)
                    {
                        throw;
                    }
                    else
                    {
                        isAvailable = false;
                        Logger?.LogError(new EventId(), ex, "Cache provider get error.");
                    }
                }

                if (cacheValue != null)
                {
                    if (context.IsAsync())
                    {
                        //#1
                        //dynamic member = context.ServiceMethod.ReturnType.GetMember("Result")[0];
                        //dynamic temp = System.Convert.ChangeType(cacheValue.Value, member.PropertyType);
                        //context.ReturnValue = System.Convert.ChangeType(Task.FromResult(temp), context.ServiceMethod.ReturnType);

                        //#2
                        context.ReturnValue =
                            TypeofTaskResultMethod.GetOrAdd(returnType, t => typeof(Task).GetMethods().First(p => p.Name == "FromResult" && p.ContainsGenericParameters).MakeGenericMethod(returnType)).Invoke(null, new object[] { cacheValue });
                    }
                    else
                    {
                        //context.ReturnValue = System.Convert.ChangeType(cacheValue.Value, context.ServiceMethod.ReturnType);
                        context.ReturnValue = cacheValue;
                    }
                }
                else
                {
                    // Invoke the method if we don't have a cache hit
                    await next(context);

                    if (isAvailable)
                    {
                        // get the result
                        var returnValue = context.IsAsync()
                            ? await context.UnwrapAsyncReturnValue()
                            : context.ReturnValue;

                        // should we do something when method return null?
                        // 1. cached a null value for a short time
                        // 2. do nothing
                        if (returnValue != null)
                        {
                            if (attribute.IsHybridProvider)
                            {
                                await HybridCachingProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                            }
                            else
                            {
                                var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                                await _cacheProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                            }
                        }
                    }
                }
            }
            else
            {
                // Invoke the method if we don't have EasyCachingAbleAttribute
                await next(context);
            }
        }
Ejemplo n.º 13
0
 public void EncodeCurveLockKeyPairBadKeyTest2()
 {
     KeyGenerator.EncodeCurveLockPublicKey(SodiumCore.GetRandomBytes(31));
 }
Ejemplo n.º 14
0
        private static void ExampleLevels()
        {
            Utilities.PrintExampleBanner("Example: Levels");

            /*
             * In this examples we describe the concept of `levels' in BFV and CKKS and the
             * related objects that represent them in Microsoft SEAL.
             *
             * In Microsoft SEAL a set of encryption parameters (excluding the random number
             * generator) is identified uniquely by a 256-bit hash of the parameters. This
             * hash is called the `ParmsId' and can be easily accessed and printed at any
             * time. The hash will change as soon as any of the parameters is changed.
             *
             * When a SEALContext is created from a given EncryptionParameters instance,
             * Microsoft SEAL automatically creates a so-called `modulus switching chain',
             * which is a chain of other encryption parameters derived from the original set.
             * The parameters in the modulus switching chain are the same as the original
             * parameters with the exception that size of the coefficient modulus is
             * decreasing going down the chain. More precisely, each parameter set in the
             * chain attempts to remove the last coefficient modulus prime from the
             * previous set; this continues until the parameter set is no longer valid
             * (e.g., PlainModulus is larger than the remaining CoeffModulus). It is easy
             * to walk through the chain and access all the parameter sets. Additionally,
             * each parameter set in the chain has a `chain index' that indicates its
             * position in the chain so that the last set has index 0. We say that a set
             * of encryption parameters, or an object carrying those encryption parameters,
             * is at a higher level in the chain than another set of parameters if its the
             * chain index is bigger, i.e., it is earlier in the chain.
             *
             * Each set of parameters in the chain involves unique pre-computations performed
             * when the SEALContext is created, and stored in a SEALContext.ContextData
             * object. The chain is basically a linked list of SEALContext.ContextData
             * objects, and can easily be accessed through the SEALContext at any time. Each
             * node can be identified by the ParmsId of its specific encryption parameters
             * (PolyModulusDegree remains the same but CoeffModulus varies).
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 8192;

            parms.PolyModulusDegree = polyModulusDegree;

            /*
             * In this example we use a custom CoeffModulus, consisting of 5 primes of
             * sizes 50, 30, 30, 50, and 50 bits. Note that this is still OK according to
             * the explanation in `1_BFV_Basics.cs'. Indeed,
             *
             *  CoeffModulus.MaxBitCount(polyModulusDegree)
             *
             * returns 218 (greater than 50+30+30+50+50=210).
             *
             * Due to the modulus switching chain, the order of the 5 primes is significant.
             * The last prime has a special meaning and we call it the `special prime'. Thus,
             * the first parameter set in the modulus switching chain is the only one that
             * involves the special prime. All key objects, such as SecretKey, are created
             * at this highest level. All data objects, such as Ciphertext, can be only at
             * lower levels. The special modulus should be as large as the largest of the
             * other primes in the CoeffModulus, although this is not a strict requirement.
             *
             *       special prime +---------+
             |
             |                               v
             | CoeffModulus: { 50, 30, 30, 50, 50 }  +---+  Level 4 (all keys; `key level')
             |
             |
             |  CoeffModulus: { 50, 30, 30, 50 }  +---+  Level 3 (highest `data level')
             |
             |
             |      CoeffModulus: { 50, 30, 30 }  +---+  Level 2
             |
             |
             |          CoeffModulus: { 50, 30 }  +---+  Level 1
             |
             |
             |              CoeffModulus: { 50 }  +---+  Level 0 (lowest level)
             */
            parms.CoeffModulus = CoeffModulus.Create(
                polyModulusDegree, new int[] { 50, 30, 30, 50, 50 });

            /*
             * In this example the PlainModulus does not play much of a role; we choose
             * some reasonable value.
             */
            parms.PlainModulus = PlainModulus.Batching(polyModulusDegree, 20);

            using SEALContext context = new SEALContext(parms);
            Utilities.PrintParameters(context);

            /*
             * There are convenience method for accessing the SEALContext.ContextData for
             * some of the most important levels:
             *
             *  SEALContext.KeyContextData: access to key level ContextData
             *  SEALContext.FirstContextData: access to highest data level ContextData
             *  SEALContext.LastContextData: access to lowest level ContextData
             *
             * We iterate over the chain and print the ParmsId for each set of parameters.
             */
            Console.WriteLine();
            Utilities.PrintLine();
            Console.WriteLine("Print the modulus switching chain.");

            /*
             * First print the key level parameter information.
             */
            SEALContext.ContextData contextData = context.KeyContextData;
            Console.WriteLine("----> Level (chain index): {0} ...... KeyContextData",
                              contextData.ChainIndex);
            Console.WriteLine($"      ParmsId: {contextData.ParmsId}");
            Console.Write("      CoeffModulus primes: ");
            foreach (Modulus prime in contextData.Parms.CoeffModulus)
            {
                Console.Write($"{Utilities.ULongToString(prime.Value)} ");
            }
            Console.WriteLine();
            Console.WriteLine("\\");
            Console.Write(" \\--> ");

            /*
             * Next iterate over the remaining (data) levels.
             */
            contextData = context.FirstContextData;
            while (null != contextData)
            {
                Console.Write($"Level (chain index): {contextData.ChainIndex}");
                if (contextData.ParmsId.Equals(context.FirstParmsId))
                {
                    Console.WriteLine(" ...... FirstContextData");
                }
                else if (contextData.ParmsId.Equals(context.LastParmsId))
                {
                    Console.WriteLine(" ...... LastContextData");
                }
                else
                {
                    Console.WriteLine();
                }
                Console.WriteLine($"      ParmsId: {contextData.ParmsId}");
                Console.Write("      CoeffModulus primes: ");
                foreach (Modulus prime in contextData.Parms.CoeffModulus)
                {
                    Console.Write($"{Utilities.ULongToString(prime.Value)} ");
                }
                Console.WriteLine();
                Console.WriteLine("\\");
                Console.Write(" \\--> ");

                /*
                 * Step forward in the chain.
                 */
                contextData = contextData.NextContextData;
            }
            Console.WriteLine("End of chain reached");
            Console.WriteLine();

            /*
             * We create some keys and check that indeed they appear at the highest level.
             */
            using KeyGenerator keygen = new KeyGenerator(context);
            using SecretKey secretKey = keygen.SecretKey;
            keygen.CreatePublicKey(out PublicKey publicKey);
            keygen.CreateRelinKeys(out RelinKeys relinKeys);

            Utilities.PrintLine();
            Console.WriteLine("Print the parameter IDs of generated elements.");
            Console.WriteLine($"    + publicKey:  {publicKey.ParmsId}");
            Console.WriteLine($"    + secretKey:  {secretKey.ParmsId}");
            Console.WriteLine($"    + relinKeys:  {relinKeys.ParmsId}");

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

            /*
             * In the BFV scheme plaintexts do not carry a ParmsId, but ciphertexts do. Note
             * how the freshly encrypted ciphertext is at the highest data level.
             */
            using Plaintext plain      = new Plaintext("1x^3 + 2x^2 + 3x^1 + 4");
            using Ciphertext encrypted = new Ciphertext();
            encryptor.Encrypt(plain, encrypted);
            Console.WriteLine($"    + plain:      {plain.ParmsId} (not set in BFV)");
            Console.WriteLine($"    + encrypted:  {encrypted.ParmsId}");
            Console.WriteLine();

            /*
             * `Modulus switching' is a technique of changing the ciphertext parameters down
             * in the chain. The function Evaluator.ModSwitchToNext always switches to the
             * next level down the chain, whereas Evaluator.ModSwitchTo switches to a parameter
             * set down the chain corresponding to a given ParmsId. However, it is impossible
             * to switch up in the chain.
             */
            Utilities.PrintLine();
            Console.WriteLine("Perform modulus switching on encrypted and print.");
            contextData = context.FirstContextData;
            Console.Write("----> ");
            while (null != contextData.NextContextData)
            {
                Console.WriteLine($"Level (chain index): {contextData.ChainIndex}");
                Console.WriteLine($"      ParmsId of encrypted: {contextData.ParmsId}");
                Console.WriteLine("      Noise budget at this level: {0} bits",
                                  decryptor.InvariantNoiseBudget(encrypted));
                Console.WriteLine("\\");
                Console.Write(" \\--> ");
                evaluator.ModSwitchToNextInplace(encrypted);
                contextData = contextData.NextContextData;
            }
            Console.WriteLine($"Level (chain index): {contextData.ChainIndex}");
            Console.WriteLine($"      ParmsId of encrypted: {contextData.ParmsId}");
            Console.WriteLine("      Noise budget at this level: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));
            Console.WriteLine("\\");
            Console.Write(" \\--> ");
            Console.WriteLine("End of chain reached");
            Console.WriteLine();

            /*
             * At this point it is hard to see any benefit in doing this: we lost a huge
             * amount of noise budget (i.e., computational power) at each switch and seemed
             * to get nothing in return. Decryption still works.
             */
            Utilities.PrintLine();
            Console.WriteLine("Decrypt still works after modulus switching.");
            decryptor.Decrypt(encrypted, plain);
            Console.WriteLine($"    + Decryption of encrypted: {plain} ...... Correct.");
            Console.WriteLine();

            /*
             * However, there is a hidden benefit: the size of the ciphertext depends
             * linearly on the number of primes in the coefficient modulus. Thus, if there
             * is no need or intention to perform any further computations on a given
             * ciphertext, we might as well switch it down to the smallest (last) set of
             * parameters in the chain before sending it back to the secret key holder for
             * decryption.
             *
             * Also the lost noise budget is actually not an issue at all, if we do things
             * right, as we will see below.
             *
             * First we recreate the original ciphertext and perform some computations.
             */
            Console.WriteLine("Computation is more efficient with modulus switching.");
            Utilities.PrintLine();
            Console.WriteLine("Compute the eight power.");
            encryptor.Encrypt(plain, encrypted);
            Console.WriteLine("    + Noise budget fresh:                  {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));
            evaluator.SquareInplace(encrypted);
            evaluator.RelinearizeInplace(encrypted, relinKeys);
            Console.WriteLine("    + Noise budget of the 2nd power:        {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));
            evaluator.SquareInplace(encrypted);
            evaluator.RelinearizeInplace(encrypted, relinKeys);
            Console.WriteLine("    + Noise budget of the 4th power:        {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));

            /*
             * Surprisingly, in this case modulus switching has no effect at all on the
             * noise budget.
             */
            evaluator.ModSwitchToNextInplace(encrypted);
            Console.WriteLine("    + Noise budget after modulus switching: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));


            /*
             * This means that there is no harm at all in dropping some of the coefficient
             * modulus after doing enough computations. In some cases one might want to
             * switch to a lower level slightly earlier, actually sacrificing some of the
             * noise budget in the process, to gain computational performance from having
             * smaller parameters. We see from the print-out that the next modulus switch
             * should be done ideally when the noise budget is down to around 25 bits.
             */
            evaluator.SquareInplace(encrypted);
            evaluator.RelinearizeInplace(encrypted, relinKeys);
            Console.WriteLine("    + Noise budget of the 8th power:        {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));
            evaluator.ModSwitchToNextInplace(encrypted);
            Console.WriteLine("    + Noise budget after modulus switching: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted));

            /*
             * At this point the ciphertext still decrypts correctly, has very small size,
             * and the computation was as efficient as possible. Note that the decryptor
             * can be used to decrypt a ciphertext at any level in the modulus switching
             * chain.
             */
            decryptor.Decrypt(encrypted, plain);
            Console.WriteLine("    + Decryption of the 8th power (hexadecimal) ...... Correct.");
            Console.WriteLine($"    {plain}");
            Console.WriteLine();

            /*
             * In BFV modulus switching is not necessary and in some cases the user might
             * not want to create the modulus switching chain, except for the highest two
             * levels. This can be done by passing a bool `false' to SEALContext constructor.
             */
            using SEALContext context2 = new SEALContext(parms, expandModChain: false);

            /*
             * We can check that indeed the modulus switching chain has been created only
             * for the highest two levels (key level and highest data level). The following
             * loop should execute only once.
             */
            Console.WriteLine("Optionally disable modulus switching chain expansion.");
            Utilities.PrintLine();
            Console.WriteLine("Print the modulus switching chain.");
            Console.Write("----> ");
            for (contextData = context2.KeyContextData; null != contextData;
                 contextData = contextData.NextContextData)
            {
                Console.WriteLine($"Level (chain index): {contextData.ChainIndex}");
                Console.WriteLine($"      ParmsId of encrypted: {contextData.ParmsId}");
                Console.Write("      CoeffModulus primes: ");
                foreach (Modulus prime in contextData.Parms.CoeffModulus)
                {
                    Console.Write($"{Utilities.ULongToString(prime.Value)} ");
                }
                Console.WriteLine();
                Console.WriteLine("\\");
                Console.Write(" \\--> ");
            }
            Console.WriteLine("End of chain reached");
            Console.WriteLine();

            /*
             * It is very important to understand how this example works since in the CKKS
             * scheme modulus switching has a much more fundamental purpose and the next
             * examples will be difficult to understand unless these basic properties are
             * totally clear.
             */
        }
Ejemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult Pay(PayViewModel payModel)
        {
            //获取产品信息
            if (payModel.OrderId.Equals(Guid.Empty))
            {
                return(Content("订单Id不合法!"));
            }

            var order = _currencyService.GetSingleById <Order>(payModel.OrderId);

            if (order == null)
            {
                return(Content("订单数据不存在!"));
            }

            if (order.OrderStatus != OrderStatus.PendingPayment && order.PayStatus != PayStatus.Unpaid)
            {
                return(Content("订单状态不合理,无法支付!"));
            }

            var payment = _paymentService.LoadPayment(payModel.PaymentCode);

            if (payment == null || !payment.Enabled)
            {
                return(Content("支付方式不合法或已停用!"));
            }

            var paymentDispatcher = HostConstObject.Container.ResolveNamed <IPaymentDispatcher>(payment.Code.ToLower());

            if (paymentDispatcher == null)
            {
                return(Content("支付方式不合法"));
            }

            var routeParas = new RouteValueDictionary {
                { "area", PaymentProcessModule.Area },
                { "controller", "Receive" },
                { "action", "AsyncReturn" },
                { "paymentCode", payment.Code }
            };
            var notifyUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas);

            var routeParas2 = new RouteValueDictionary {
                { "area", PaymentProcessModule.Area },
                { "controller", "Receive" },
                { "action", "SyncReturn" },
                { "paymentCode", payment.Code }
            };
            var returnUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas2);

            if (payModel.UseBalance == 1)
            {
                //使用余额付款
                #region

                using (TransactionScope scope = new TransactionScope())
                {
                    var cashWallet = _walletService.GetWalletByMemberId(order.MemberId,
                                                                        Wallet.Models.WalletType.Cash);
                    if (cashWallet != null && cashWallet.Available > 0)
                    {
                        if (cashWallet.Available >= order.PayFee)
                        {
                            string error;
                            if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee,
                                                    "支付订单" + order.OrderNo, out error))
                            {
                                order.BalancePay  = order.PayFee;
                                order.OrderStatus = OrderStatus.WaitingForDelivery;
                                order.PayStatus   = PayStatus.Paid;
                                order.PayTime     = DateTime.Now;

                                var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString());
                                order.PaymentId   = balancePayment.Id;
                                order.PaymentName = balancePayment.Name;
                                _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                                _currencyService.Update(order);

                                scope.Complete();
                            }
                        }
                        else
                        {
                            string error;
                            if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash,
                                                    cashWallet.Available,
                                                    "支付订单" + order.OrderNo, out error))
                            {
                                order.UnpayFee   = order.PayFee - cashWallet.Available;
                                order.BalancePay = cashWallet.Available;
                                _currencyService.Update(order);

                                scope.Complete();
                            }
                        }
                    }
                }

                #endregion
            }

            if (order.PayStatus == PayStatus.Paid)
            {
                return(Redirect(_publicService.GetReturnUrl(order.Id)));
            }

            var payLog = new PayLog
            {
                Id            = KeyGenerator.GetGuidKey(),
                TransactionNo = $"{order.OrderNo}{KeyGenerator.GenerateRandom(1000, 1)}",
                OrderId       = order.Id,
                OrderNo       = order.OrderNo,
                OrderAmount   = order.UnpayFee,
                PaymentId     = payment.Id,
                PaymentName   = payment.Name,
                CreateTime    = DateTime.Now,
                LogStatus     = LogStatus.Unpaid
            };
            if (!_currencyService.Create(payLog))
            {
                throw new WebApiInnerException("0007", "生成支付流水失败");
            }

            var subject = $"支付订单{order.OrderNo}-{payLog.TransactionNo}";
            var body    = string.Join(";", _currencyService.GetList <OrderGoods>(x => x.OrderId == order.Id).Select(g => g.GoodsName));

            ViewBag.Html = paymentDispatcher.H5Pay(subject, body, notifyUrl, returnUrl, payLog, payment);

            return(View());
        }
        private void UpdateContext(KerberosAsResponse response)
        {
            KerberosFastResponse kerbFastRep = null;

            if (response.Response.padata != null && response.Response.padata.Elements != null)
            {
                foreach (PA_DATA paData in response.Response.padata.Elements)
                {
                    var parsedPaData = PaDataParser.ParseRepPaData(paData);
                    if (parsedPaData is PaETypeInfo2)
                    {
                        Asn1DecodingBuffer buffer     = new Asn1DecodingBuffer(paData.padata_value.ByteArrayValue);
                        ETYPE_INFO2        eTypeInfo2 = new ETYPE_INFO2();
                        eTypeInfo2.BerDecode(buffer);
                        if (eTypeInfo2.Elements != null && eTypeInfo2.Elements.Length > 0)
                        {
                            // the salt is received from KDC
                            if (eTypeInfo2.Elements[0].salt != null)
                            {
                                Context.CName.Salt = eTypeInfo2.Elements[0].salt.Value;
                            }
                            continue;
                        }
                    }
                    if (parsedPaData is PaFxFastRep)
                    {
                        var armoredRep = ((PaFxFastRep)parsedPaData).GetArmoredRep();
                        kerbFastRep = ((PaFxFastRep)parsedPaData).GetKerberosFastRep(Context.FastArmorkey);
                        var strKey = kerbFastRep.FastResponse.strengthen_key;
                        Context.ReplyKey = KerberosUtility.KrbFxCf2(
                            strKey,
                            //Fix me: should be Context.ReplyKey
                            KerberosUtility.MakeKey(Context.SelectedEType, Context.CName.Password, Context.CName.Salt),
                            "strengthenkey",
                            "replykey");
                    }
                }
            }

            if (Context.ReplyKey != null)
            {
                response.Decrypt(Context.ReplyKey.keyvalue.ByteArrayValue);
            }
            else
            {
                var encryptType = (EncryptionType)response.Response.enc_part.etype.Value;
                var key         = KeyGenerator.MakeKey(encryptType, Context.CName.Password, Context.CName.Salt);
                Context.ReplyKey = new EncryptionKey(new KerbInt32((long)encryptType), new Asn1OctetString(key));
                response.Decrypt(key);
            }

            if (response.EncPart != null)
            {
                Context.SessionKey = response.EncPart.key;
            }

            if (response.Response != null)
            {
                //Response.Response.cname is not the real CName of the ticket when hide-client-names=1
                if (kerbFastRep != null && kerbFastRep.FastResponse != null && kerbFastRep.FastResponse.finished != null)
                {
                    // Windows DC is case insensitive. It may change the cname in the response, e.g. administrator -> Administrator
                    Context.CName.Name = kerbFastRep.FastResponse.finished.cname;
                    Context.Ticket     = new KerberosTicket(response.Response.ticket, kerbFastRep.FastResponse.finished.cname, response.EncPart.key);
                }
                else
                {
                    // Windows DC is case insensitive. It may change the cname in the response, e.g. administrator -> Administrator
                    Context.CName.Name = response.Response.cname;
                    Context.Ticket     = new KerberosTicket(response.Response.ticket, response.Response.cname, response.EncPart.key);
                }
                Context.SelectedEType = (EncryptionType)Context.Ticket.SessionKey.keytype.Value;
                if (Context.Ticket != null && Context.Ticket.Ticket.sname != null &&
                    Context.Ticket.Ticket.sname.name_string != null &&
                    Context.Ticket.Ticket.sname.name_string.Elements != null &&
                    Context.Ticket.Ticket.sname.name_string.Elements.Length > 1)
                {
                    int count = Context.Ticket.Ticket.sname.name_string.Elements.Length;
                    Context.Realm = new Realm(Context.Ticket.Ticket.sname.name_string.Elements[count - 1].Value);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Test the StreamMac class implementation
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void StreamMacTest()
        {
            byte[] data;
            byte[] key;
            MemoryStream instrm;
            MemoryStream outstrm = new MemoryStream();

            using (KeyGenerator kg = new KeyGenerator())
            {
                data = kg.GetBytes(512);
                key = kg.GetBytes(64);
            }

            // data to digest
            instrm = new MemoryStream(data);
            byte[] code1;
            byte[] code2;

            using (StreamMac sm = new StreamMac(new SHA512HMAC(key)))
            {
                sm.Initialize(instrm);
                code1 = sm.ComputeMac();
            }

            using (HMAC hm = new HMAC(new SHA512()))
            {
                hm.Initialize(new KeyParams(key));
                code2 = hm.ComputeMac(data);
            }

            // compare the hash codes
            if (!Compare.AreEqual(code1, code2))
                throw new Exception();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Test the StreamDigest class implementation
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void StreamDigestTest()
        {
            byte[] data;
            MemoryStream instrm;
            MemoryStream outstrm = new MemoryStream();

            using (KeyGenerator kg = new KeyGenerator())
                data = kg.GetBytes(512);

            // data to digest
            instrm = new MemoryStream(data);
            byte[] code1;
            byte[] code2;

            using (StreamDigest sd = new StreamDigest(Digests.Keccak512))
            {
                sd.Initialize(instrm);
                code1 = sd.ComputeHash();
            }

            using (Keccak512 kc = new Keccak512())
                code2 = kc.ComputeHash(data);

            // compare the hash codes
            if (!Compare.AreEqual(code1, code2))
                throw new Exception();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Test the StreamCipher class implementation
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void StreamCipherTest()
        {
            const int BLSZ = 1024;
            KeyParams key;
            byte[] data;
            MemoryStream instrm;
            MemoryStream outstrm = new MemoryStream();

            using (KeyGenerator kg = new KeyGenerator())
            {
                // get the key
                key = kg.GetKeyParams(32, 16);
                // 2048 bytes
                data = kg.GetBytes(BLSZ * 2);
            }
            // data to encrypt
            instrm = new MemoryStream(data);

            // Encrypt a stream //
            // create the outbound cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for encryption
                cipher.Initialize(true, key);
                // set block size
                ((CTR)cipher).ParallelBlockSize = BLSZ;

                // encrypt the stream
                using (StreamCipher sc = new StreamCipher(cipher))
                {
                    sc.Initialize(instrm, outstrm);
                    // encrypt the buffer
                    sc.Write();
                }
            }

            // reset stream position
            outstrm.Seek(0, SeekOrigin.Begin);
            MemoryStream tmpstrm = new MemoryStream();

            // Decrypt a stream //
            // create the decryption cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for decryption
                cipher.Initialize(false, key);
                // set block size
                ((CTR)cipher).ParallelBlockSize = BLSZ;

                // decrypt the stream
                using (StreamCipher sc = new StreamCipher(cipher))
                {
                    sc.Initialize(outstrm, tmpstrm);
                    // process the encrypted bytes
                    sc.Write();
                }
            }

            // compare decrypted output with data
            if (!Compare.AreEqual(tmpstrm.ToArray(), data))
                throw new Exception();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create a unique id for this installation
        /// </summary>
        /// 
        /// <returns>Unique machine Id</returns>
        private byte[] IdGenerator()
        {
            byte[] localId = new byte[16];

            // create a unique machine id, in an organization this would be assigned
            using (KeyGenerator gen = new KeyGenerator())
                gen.GetBytes(localId);

            return localId;
        }
Ejemplo n.º 21
0
        private void ELFFileKeyGeneratorInternal(bool fileGenerator)
        {
            using (Stream stream = TestUtilities.OpenCompressedFile("TestBinaries/libcoreclr.so.gz"))
            {
                var          file      = new SymbolStoreFile(stream, "libcoreclr.so");
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new ELFFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "libcoreclr.so/elf-buildid-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libcoreclr.so");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 1);
                Assert.True(symbolKey.First().Index == "_.debug/elf-buildid-sym-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/_.debug");

                Dictionary <string, SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys).ToDictionary((key) => key.Index);
                Assert.True(clrKeys.ContainsKey("libmscordaccore.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libmscordaccore.so"));
                Assert.True(clrKeys.ContainsKey("libmscordbi.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libmscordbi.so"));
                Assert.True(clrKeys.ContainsKey("mscordaccore.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/mscordaccore.dll"));
                Assert.True(clrKeys.ContainsKey("mscordbi.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/mscordbi.dll"));
                Assert.True(clrKeys.ContainsKey("libsos.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libsos.so"));
                Assert.True(clrKeys.ContainsKey("sos.netcore.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/sos.netcore.dll"));

                Dictionary <string, SymbolStoreKey> dacdbiKeys = generator.GetKeys(KeyTypeFlags.DacDbiKeys).ToDictionary((key) => key.Index);
                Assert.True(dacdbiKeys.ContainsKey("libmscordaccore.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libmscordaccore.so"));
                Assert.True(dacdbiKeys.ContainsKey("libmscordbi.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libmscordbi.so"));
                Assert.True(dacdbiKeys.ContainsKey("mscordaccore.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/mscordaccore.dll"));
                Assert.True(dacdbiKeys.ContainsKey("mscordbi.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/mscordbi.dll"));
                Assert.False(dacdbiKeys.ContainsKey("libsos.so/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/libsos.so"));
                Assert.False(dacdbiKeys.ContainsKey("sos.netcore.dll/elf-buildid-coreclr-ef8f58a0b402d11c68f78342ef4fcc7d23798d4c/sos.netcore.dll"));
            }

            using (Stream stream = TestUtilities.OpenCompressedFile("TestBinaries/libcoreclrtraceptprovider.so.dbg.gz"))
            {
                var          file      = new SymbolStoreFile(stream, "libcoreclrtraceptprovider.so.dbg");
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new ELFFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "_.debug/elf-buildid-sym-ce4ce0558d878a05754dff246ccea2a70a1db3a8/_.debug");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 0);

                IEnumerable <SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys);
                Assert.True(clrKeys.Count() == 0);
            }

            using (Stream stream = File.OpenRead("TestBinaries/symbolized_executable"))
            {
                var          file      = new SymbolStoreFile(stream, "symbolized_executable");
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new ELFFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "_.debug/elf-buildid-sym-126ba1461caf6644cfdd124bfcceeffa81b18897/_.debug");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 0);

                IEnumerable <SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys);
                Assert.True(clrKeys.Count() == 0);
            }

            using (Stream stream = File.OpenRead("TestBinaries/stripped_executable"))
            {
                var          file      = new SymbolStoreFile(stream, "stripped_executable");
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new ELFFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "stripped_executable/elf-buildid-126ba1461caf6644cfdd124bfcceeffa81b18897/stripped_executable");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 1);
                Assert.True(symbolKey.First().Index == "_.debug/elf-buildid-sym-126ba1461caf6644cfdd124bfcceeffa81b18897/_.debug");

                IEnumerable <SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys);
                Assert.True(clrKeys.Count() == 0);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Test the PacketCipher class implementation
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void PacketCipherTest()
        {
            const int BLSZ = 1024;
            KeyParams key;
            byte[] data;
            MemoryStream instrm;
            MemoryStream outstrm = new MemoryStream();

            using (KeyGenerator kg = new KeyGenerator())
            {
                // get the key
                key = kg.GetKeyParams(32, 16);
                // 2 * 1200 byte packets
                data = kg.GetBytes(BLSZ * 2);
            }
            // data to encrypt
            instrm = new MemoryStream(data);

            // Encrypt a stream //
            // create the outbound cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for encryption
                cipher.Initialize(true, key);
                // set block size
                ((CTR)cipher).ParallelBlockSize = BLSZ;

                // encrypt the stream
                using (PacketCipher pc = new PacketCipher(cipher))
                {
                    byte[] inbuffer = new byte[BLSZ];
                    byte[] outbuffer = new byte[BLSZ];
                    int bytesread = 0;

                    while ((bytesread = instrm.Read(inbuffer, 0, BLSZ)) > 0)
                    {
                        // encrypt the buffer
                        pc.Write(inbuffer, 0, outbuffer, 0, BLSZ);
                        // add it to the output stream
                        outstrm.Write(outbuffer, 0, outbuffer.Length);
                    }
                }
            }

            // reset stream position
            outstrm.Seek(0, SeekOrigin.Begin);
            MemoryStream tmpstrm = new MemoryStream();

            // Decrypt a stream //
            // create the inbound cipher
            using (ICipherMode cipher = new CTR(new RDX()))
            {
                // initialize the cipher for decryption
                cipher.Initialize(false, key);
                // set block size
                ((CTR)cipher).ParallelBlockSize = BLSZ;

                // decrypt the stream
                using (PacketCipher pc = new PacketCipher(cipher))
                {
                    byte[] inbuffer = new byte[BLSZ];
                    byte[] outbuffer = new byte[BLSZ];
                    int bytesread = 0;

                    while ((bytesread = outstrm.Read(inbuffer, 0, BLSZ)) > 0)
                    {
                        // process the encrypted bytes
                        pc.Write(inbuffer, 0, outbuffer, 0, BLSZ);
                        // write to stream
                        tmpstrm.Write(outbuffer, 0, outbuffer.Length);
                    }
                }
            }

            // compare decrypted output with data
            if (!Compare.AreEqual(tmpstrm.ToArray(), data))
                throw new Exception();
        }
Ejemplo n.º 23
0
    public string Create(string value, string salt)
    {
        using var key = KeyGenerator.Generate(value, salt);

        return(Convert.ToBase64String(key.GetBytes(512)));
    }
Ejemplo n.º 24
0
        /// <summary>
        /// Create a volume key file using automatic key material generation.
        /// <para>The Key, and IV sets are generated automatically using the cipher description contained in the <see cref="CipherDescription"/>.
        /// This overload creates keying material using the seed and digest engines specified with the <see cref="KeyGenerator"/> class</para>
        /// </summary>
        /// 
        /// <param name="Key">The <see cref="VolumeKey">VolumeKey</see> containing the cipher and key implementation details</param>
        /// <param name="SeedEngine">The <see cref="Prngs">Random Generator</see> used to create the stage I seed material during key generation.</param>
        /// <param name="HashEngine">The <see cref="Digests">Digest Engine</see> used in the stage II phase of key generation.</param>
        /// 
        /// <exception cref="System.IO.FileLoadException">A key file exists at the path specified</exception>
        /// <exception cref="System.UnauthorizedAccessException">The key file path is read only</exception>
        public void Create(VolumeKey Key, Prngs SeedEngine = Prngs.CSPRng, Digests HashEngine = Digests.SHA512)
        {
            int ksize = Key.Count * (Key.Description.KeySize + Key.Description.IvSize);
            byte[] kdata;

            using (KeyGenerator keyGen = new KeyGenerator(SeedEngine, HashEngine))
                kdata = keyGen.GetBytes(ksize);

            if (_keyStream == null)
                _keyStream = new FileStream(_keyPath, FileMode.Create, FileAccess.Write);

            byte[] hdr = Key.ToBytes();
            _keyStream.Write(hdr, 0, hdr.Length);
            _keyStream.Write(kdata, 0, kdata.Length);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a temporary PackageKey on disk, extracts and compares the copy
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void PackageFactoryTest()
        {
            string path = GetTempPath();
            KeyGenerator kgen = new KeyGenerator();
            // populate a KeyAuthority structure
            KeyAuthority authority = new KeyAuthority(kgen.GetBytes(16), kgen.GetBytes(16), kgen.GetBytes(16), kgen.GetBytes(32), 0);

            // cipher paramaters
            CipherDescription desc = new CipherDescription(
                SymmetricEngines.RDX, 32,
                IVSizes.V128,
                CipherModes.CTR,
                PaddingModes.X923,
                BlockSizes.B128,
                RoundCounts.R14,
                Digests.Keccak512,
                64,
                Digests.Keccak512);

            // create the package key
            PackageKey pkey = new PackageKey(authority, desc, 10);

            // write a key file
            using (PackageFactory pf = new PackageFactory(path, authority))
                pf.Create(pkey);

            for (int i = 0; i < pkey.SubKeyCount; i++)
            {
                CipherDescription desc2;
                KeyParams kp1;
                KeyParams kp2;
                byte[] ext;
                byte[] id = pkey.SubKeyID[i];

                // get at index
                using (FileStream stream = new FileStream(path, FileMode.Open))
                    kp2 = PackageKey.AtIndex(stream, i);

                // read the package from id
                using (PackageFactory pf = new PackageFactory(path, authority))
                    pf.Extract(id, out desc2, out kp1, out ext);

                // compare key material
                if (!Compare.AreEqual(kp1.Key, kp2.Key))
                    throw new Exception();
                if (!Compare.AreEqual(kp1.IV, kp2.IV))
                    throw new Exception();
                if (!Compare.AreEqual(pkey.ExtensionKey, ext))
                    throw new Exception();
                if (!desc.Equals(desc2))
                    throw new Exception();
            }
            if (File.Exists(path))
                File.Delete(path);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 默认上传管理器
 /// </summary>
 public UploadManager()
 {
     this.resumeRecorder = null;
     this.keyGenerator = null;
 }
Ejemplo n.º 27
0
 public void EncodeCurveLockKeyPairBadKeyTest()
 {
     KeyGenerator.EncodeCurveLockPublicKey(null);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// 以指定的分片上传进度记录器和分片上传记录文件名构建上传管理器
 /// 
 /// 可以指定这两个参数来使分片上传支持断点续传功能
 /// </summary>
 /// <param name="recorder">分片上传进度记录器</param>
 /// <param name="generator">分片上传进度记录文件名</param>
 public UploadManager(ResumeRecorder recorder, KeyGenerator generator)
 {
     this.resumeRecorder = recorder;
     this.keyGenerator = generator;
 }
Ejemplo n.º 29
0
 public void DecodeCurveLockIdInvalidTest()
 {
     KeyGenerator.DecodeCurveLockPublicKey("5bEJLKdSib9kWxkmskExaaLdRg8tVA2qsFBnfdQwkMe");
 }
Ejemplo n.º 30
0
        /// <summary>
        /// 新建公司
        /// </summary>
        /// <param name="company">公司实体对象</param>
        /// <param name="tran">中间事务对象</param>
        /// <returns>返回处理后的公司实体对象</returns>
        public Company Add(Company company, ICTransaction tran)
        {
            if (company == null)
            {
                throw new ArgumentNullException("company");
            }

            company.CompanyId = KeyGenerator.GenNewGuidKey();
            StringBuilder query = new StringBuilder();

            query.AppendLine(@"INSERT INTO ");
            query.AppendLine(@"  [Company] ( ");
            query.AppendLine(@"     [CompanyId] ");
            query.AppendLine(@"    ,[CompanyCode] ");
            query.AppendLine(@"    ,[Name] ");
            query.AppendLine(@"    ,[Address] ");
            query.AppendLine(@"    ,[ParentCompanyId] ");
            query.AppendLine(@"    ,[RVersion] ");
            query.AppendLine(@"    ,[Status] ");
            query.AppendLine(@"    ,[CreaterId] ");
            query.AppendLine(@"    ,[CreateTime] ");
            query.AppendLine(@"    ,[UpdatorId] ");
            query.AppendLine(@"    ,[UpdateTime] ");
            query.AppendLine(@"  ) ");
            query.AppendLine(@"VALUES ( ");
            query.AppendLine(@"     @CompanyId ");
            query.AppendLine(@"    ,@CompanyCode ");
            query.AppendLine(@"    ,@Name ");
            query.AppendLine(@"    ,@Address ");
            query.AppendLine(@"    ,@ParentCompanyId ");
            query.AppendLine(@"    ,@RVersion ");
            query.AppendLine(@"    ,@Status ");
            query.AppendLine(@"    ,@CreaterId ");
            query.AppendLine(@"    ,@CreateTime ");
            query.AppendLine(@"    ,@UpdatorId ");
            query.AppendLine(@"    ,@UpdateTime ");
            query.AppendLine(@"); ");

            DBParamCollection <DBParam> paramCollection = new DBParamCollection <DBParam>();

            paramCollection.Add(new DBParam("@CompanyId", company.CompanyId, DbType.String, 40));
            paramCollection.Add(new DBParam("@CompanyCode", company.CompanyCode, DbType.String, 5));
            paramCollection.Add(new DBParam("@Name", company.Name, DbType.String, 200));
            paramCollection.Add(new DBParam("@Address", company.Address, DbType.String, 500));
            paramCollection.Add(new DBParam("@ParentCompanyId", company.ParentCompanyId, DbType.String, 40));
            paramCollection.Add(new DBParam("@RVersion", company.RVersion, DbType.Int32));
            paramCollection.Add(new DBParam("@Status", company.Status, DbType.Int32));
            paramCollection.Add(new DBParam("@CreaterId", company.CreaterId, DbType.String, 40));
            paramCollection.Add(new DBParam("@CreateTime", company.CreateTime, DbType.DateTime));
            paramCollection.Add(new DBParam("@UpdatorId", company.UpdatorId, DbType.String, 40));
            paramCollection.Add(new DBParam("@UpdateTime", company.UpdateTime, DbType.DateTime));

            try
            {
                int effectCount = 0;

                if (company != null)
                {
                    if (tran != null)
                    {
                        DbTransaction dbTran = ((MssqlTransaction)tran).CurrentTransaction;
                        effectCount = MssqlHelper.ExecuteNonQuery(dbTran, CommandType.Text, query.ToString(), paramCollection);
                    }
                    else
                    {
                        effectCount = MssqlHelper.ExecuteNonQuery(this.CurrentConnectionString, CommandType.Text, query.ToString(), paramCollection);
                    }
                }

                if (effectCount == 0)
                {
                    company.CompanyId = string.Empty;
                    throw new ResponseException((int)ResultCode.NoDataInsert, company.CompanyCode);
                }
            }
            catch (Exception ex)
            {
                company.CompanyId = string.Empty;
                throw new Exception(ex.Message, ex);
            }

            return(company);
        }
Ejemplo n.º 31
0
 public void SetUp()
 {
     rsaes_pkcs1  = new RSAES_PKCS1();
     keyGenerator = new KeyGenerator();
 }
Ejemplo n.º 32
0
        public void ScaleTest()
        {
            List <SmallModulus> coeffModulus = new List <SmallModulus>()
            {
                DefaultParams.SmallMods40Bit(0),
                DefaultParams.SmallMods40Bit(1),
                DefaultParams.SmallMods40Bit(2),
                DefaultParams.SmallMods40Bit(3)
            };
            EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS)
            {
                CoeffModulus      = coeffModulus,
                PolyModulusDegree = 8
            };
            SEALContext  context    = SEALContext.Create(parms);
            KeyGenerator keygen     = new KeyGenerator(context);
            GaloisKeys   galoisKeys = keygen.GaloisKeys(decompositionBitCount: 4);
            Encryptor    encryptor  = new Encryptor(context, keygen.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, parms.ParmsId, 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);
        }
Ejemplo n.º 33
0
        public void method_2()
        {
            this.delegate9_0(0, "*.tex.xen");
            TreeNode treeNode = new TreeNode("Data");

            string[] files = Directory.GetFiles(this.string_0.Remove(this.string_0.Length - 1), "*.tex.xen", SearchOption.AllDirectories);
            string[] array = files;
            for (int i = 0; i < array.Length; i++)
            {
                string text = array[i];
                this.method_3(treeNode, new List <string>(text.Substring(this.string_0.Length).Split(new char[]
                {
                    '\\',
                    '/'
                }, StringSplitOptions.RemoveEmptyEntries))).ToolTipText = text;
            }
            this.delegate9_0(1, "*.img.xen");
            files = Directory.GetFiles(this.string_0.Remove(this.string_0.Length - 1), "*.img.xen", SearchOption.AllDirectories);
            string[] array2 = files;
            for (int j = 0; j < array2.Length; j++)
            {
                string text2 = array2[j];
                this.method_3(treeNode, new List <string>(text2.Substring(this.string_0.Length).Split(new char[]
                {
                    '\\',
                    '/'
                }, StringSplitOptions.RemoveEmptyEntries))).ToolTipText = text2;
            }
            int num  = QbSongClass1.smethod_9(".tex");
            int num2 = QbSongClass1.smethod_9(".img");

            files = Directory.GetFiles(this.string_0.Remove(this.string_0.Length - 1), "*.pak.xen", SearchOption.AllDirectories);
            int num3 = 0;

            string[] array3 = files;
            for (int k = 0; k < array3.Length; k++)
            {
                string text3 = array3[k];
                this.delegate9_0(1 + (int)(98.0 * (double)(++num3) / (double)files.Length), KeyGenerator.GetFileName(text3));
                try
                {
                    using (zzPakNode2 @class = File.Exists(text3.Replace(".pak.xen", ".pab.xen")) ? new zzPabNode(text3, text3.Replace(".pak.xen", ".pab.xen"), false) : new zzPakNode2(text3, false))
                    {
                        List <TreeNode> list = new List <TreeNode>();
                        foreach (Interface12 current in @class.list_0)
                        {
                            int num4 = current.imethod_7();
                            if (current.imethod_4() == num || current.imethod_4() == num2)
                            {
                                list.Add(new TreeNode(QbSongClass1.smethod_3(num4) ? KeyGenerator.GetFileName(QbSongClass1.smethod_5(num4)) : KeyGenerator.ValToHex32bit(num4))
                                {
                                    ToolTipText = text3,
                                    Tag         = num4
                                });
                            }
                        }
                        if (list.Count > 0)
                        {
                            this.method_3(treeNode, new List <string>(text3.Substring(this.string_0.Length).Split(new char[]
                            {
                                '\\',
                                '/'
                            }, StringSplitOptions.RemoveEmptyEntries))).Nodes.AddRange(list.ToArray());
                        }
                    }
                }
                catch
                {
                }
                GC.Collect();
            }
            this.delegate8_0(treeNode);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Create a key file using a <see cref="PackageKey"/> structure; containing the cipher description and operating ids and flags.
        /// </summary>
        /// 
        /// <param name="Package">The <see cref="PackageKey">Key Header</see> containing the cipher description and operating ids and flags</param>
        /// <param name="SeedEngine">The <see cref="Prngs">Random Generator</see> used to create the stage I seed material during key generation.</param>
        /// <param name="DigestEngine">The <see cref="Digests">Digest Engine</see> used in the stage II phase of key generation.</param>
        /// 
        /// <exception cref="CryptoProcessingException">Thrown if a key file exists at the path specified, the path is read only, the CipherDescription or KeyAuthority structures are invalid, or
        /// number of SubKeys specified is either less than 1 or more than the maximum allowed (100,000)</exception>
        public void Create(PackageKey Package, Prngs SeedEngine = Prngs.CSPRng, Digests DigestEngine = Digests.SHA512)
        {
            // if you are getting exceptions.. read the docs!
            if (File.Exists(_keyPath))
                throw new CryptoProcessingException("PackageFactory:Create", "The key file exists! Can not overwrite an existing key file, choose a different path.", new FileLoadException());
            if (!DirectoryTools.IsWritable(Path.GetDirectoryName(_keyPath)))
                throw new CryptoProcessingException("PackageFactory:Create", "The selected directory is read only! Choose a different path.", new UnauthorizedAccessException());
            if (!CipherDescription.IsValid(Package.Description))
                throw new CryptoProcessingException("PackageFactory:Create", "The key package cipher settings are invalid!", new FormatException());
            if (!KeyAuthority.IsValid(Package.Authority))
                throw new CryptoProcessingException("PackageFactory:Create", "The key package key authority settings are invalid!", new FormatException());
            if (Package.SubKeyCount < 1)
                throw new CryptoProcessingException("PackageFactory:Create", "The key package must contain at least 1 key!", new ArgumentOutOfRangeException());
            if (Package.SubKeyCount > SUBKEY_MAX)
                throw new CryptoProcessingException("PackageFactory:Create", String.Format("The key package can not contain more than {0} keys!", SUBKEY_MAX), new ArgumentOutOfRangeException());

            // get the size of a subkey set
            int subKeySize = Package.Description.KeySize;

            if (Package.Description.IvSize > 0)
                subKeySize += Package.Description.IvSize;

            if (Package.Description.MacSize > 0)
                subKeySize += Package.Description.MacSize;

            if (subKeySize < 0)
                throw new CryptoProcessingException("PackageFactory:Create", "The key package cipher settings are invalid!", new Exception());

            try
            {
                // store the auth struct and policy
                _keyOwner = Package.Authority;
                this.KeyPolicy = Package.KeyPolicy;
                // get the serialized header
                byte[] header = Package.ToBytes();
                // size key buffer
                byte[] buffer = new byte[subKeySize * Package.SubKeyCount];

                // generate the keying material
                using (KeyGenerator keyGen = new KeyGenerator(SeedEngine, DigestEngine))
                    keyGen.GetBytes(buffer);

                using (BinaryWriter keyWriter = new BinaryWriter(new FileStream(_keyPath, FileMode.Create, FileAccess.Write)))
                {
                    // pre-set the size to avoid fragmentation
                    keyWriter.BaseStream.SetLength(PackageKey.GetHeaderSize(Package) + (subKeySize * Package.SubKeyCount));

                    if (IsEncrypted(Package.KeyPolicy))
                    {
                        // add policy flags, only part of key not encrypted
                        keyWriter.Write(Package.KeyPolicy);
                        // get salt, return depends on auth flag settings
                        byte[] salt = GetSalt();
                        // create a buffer for encrypted data
                        int hdrLen = header.Length - PackageKey.GetPolicyOffset();
                        byte[] data = new byte[buffer.Length + hdrLen];
                        // copy header and key material
                        Buffer.BlockCopy(header, PackageKey.GetPolicyOffset(), data, 0, hdrLen);
                        Buffer.BlockCopy(buffer, 0, data, hdrLen, buffer.Length);
                        // encrypt the key and header
                        TransformBuffer(data, salt);
                        // write to file
                        keyWriter.Write(data);
                        // don't wait for gc
                        Array.Clear(salt, 0, salt.Length);
                        Array.Clear(data, 0, data.Length);
                    }
                    else
                    {
                        // write the keypackage header
                        keyWriter.Write(header, 0, header.Length);
                        // write the keying material
                        keyWriter.Write(buffer, 0, buffer.Length);
                    }
                }
                // cleanup
                Array.Clear(header, 0, header.Length);
                Array.Clear(buffer, 0, buffer.Length);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 35
0
        public override AbstractTreeNode1 vmethod_12(int int_0)
        {
            if (int_0 == 256)
            {
                return(new StructureHeaderNode());
            }
            int num  = int_0 >> 16 & 255;
            int num2 = int_0 >> 8 & 255;

            if (num == 32)
            {
                this.bool_1 = true;
            }
            else if (num == 4)
            {
                this.bool_1 = false;
            }
            Exception ex = new Exception("No QB Node class found for : " + KeyGenerator.ValToHex32bit(int_0));

            if (num != 32)
            {
                if (num != 4)
                {
                    if (num == 1)
                    {
                        if (num2 == 0)
                        {
                            return(new FloatListNode());
                        }
                        if (num2 == 1)
                        {
                            return(new IntegerArrayNode());
                        }
                        if (num2 == 2)
                        {
                            return(new FloatArrayNode());
                        }
                        if (num2 == 3)
                        {
                            return(new AsciiArrayNode());
                        }
                        if (num2 == 4)
                        {
                            return(new UnicodeArrayNode());
                        }
                        if (num2 == 5)
                        {
                            return(new PairArrayNode());
                        }
                        if (num2 == 6)
                        {
                            return(new VectorArrayNode());
                        }
                        if (num2 == 10)
                        {
                            return(new StructureArrayNode());
                        }
                        if (num2 == 12)
                        {
                            return(new ListArrayNode());
                        }
                        if (num2 == 13)
                        {
                            return(new TagArray());
                        }
                        if (num2 == 26)
                        {
                            this.bool_2 = true;
                            return(new FileTagArrayNode());
                        }
                        if (num2 == 28)
                        {
                            this.bool_2 = true;
                            return(new TextArrayNode());
                        }
                        throw ex;
                    }
                    else if (!this.bool_1)
                    {
                        if (num == 3)
                        {
                            return(new IntegerStructureNode());
                        }
                        if (num == 5)
                        {
                            return(new FloatStructureNode());
                        }
                        if (num == 7)
                        {
                            return(new AsciiStructureNode());
                        }
                        if (num == 9)
                        {
                            return(new UnicodeStructureNode());
                        }
                        if (num == 11)
                        {
                            return(new PairPointerNode());
                        }
                        if (num == 13)
                        {
                            return(new VectorPointerNode());
                        }
                        if (num == 21)
                        {
                            return(new StructurePointerNode());
                        }
                        if (num == 25)
                        {
                            return(new ArrayPointerNode());
                        }
                        if (num == 27)
                        {
                            return(new TagStructureNode());
                        }
                        if (num == 53)
                        {
                            return(new FileTagStructureNode());
                        }
                        throw ex;
                    }
                    else
                    {
                        if (num == 154)
                        {
                            return(new FileTagStructureNode());
                        }
                        if ((num & 240) != 128 || (num2 = (num & 15)) == 0)
                        {
                            return(null);
                        }
                        if (num2 == 1)
                        {
                            return(new IntegerStructureNode());
                        }
                        if (num2 == 2)
                        {
                            return(new FloatStructureNode());
                        }
                        if (num2 == 3)
                        {
                            return(new AsciiStructureNode());
                        }
                        if (num2 == 4)
                        {
                            return(new UnicodeStructureNode());
                        }
                        if (num2 == 5)
                        {
                            return(new PairPointerNode());
                        }
                        if (num2 == 6)
                        {
                            return(new VectorPointerNode());
                        }
                        if (num2 == 10)
                        {
                            return(new StructurePointerNode());
                        }
                        if (num2 == 12)
                        {
                            return(new ArrayPointerNode());
                        }
                        if (num2 == 13)
                        {
                            return(new TagStructureNode());
                        }
                        throw ex;
                    }
                }
            }
            if (num2 == 1)
            {
                return(new IntegerRootNode());
            }
            if (num2 == 2)
            {
                return(new FloatRootNode());
            }
            if (num2 == 3)
            {
                return(new AsciiRootNode());
            }
            if (num2 == 4)
            {
                return(new UnicodeRootNode());
            }
            if (num2 == 5)
            {
                return(new PairPointerRootNode());
            }
            if (num2 == 6)
            {
                return(new VectorPointerRootNode());
            }
            if (num2 == 7)
            {
                return(new ScriptRootNode());
            }
            if (num2 == 10)
            {
                return(new StructurePointerRootNode());
            }
            if (num2 == 12)
            {
                return(new ArrayPointerRootNode());
            }
            if (num2 == 13)
            {
                return(new TagRootNode());
            }
            if (num2 == 26)
            {
                this.bool_2 = true;
                return(new FileTagRootNode());
            }
            if (num2 == 28)
            {
                this.bool_2 = true;
                return(new TextRootNode());
            }
            throw ex;
        }
 public Product GetFirstTestProduct()
 {
     return(CreateProduct(FirstProductName, KeyGenerator.GenerateProductKey(FirstProductName)));
 }
Ejemplo n.º 37
0
 public zzGenericNode1(string string_0, IEnumerable <AbstractTreeNode1> ienumerable_0)
 {
     base.Text = KeyGenerator.GetFileName(string_0);
     base.Nodes.AddRange(new List <AbstractTreeNode1>(ienumerable_0).ToArray());
 }
 public Product GetSecondTestProduct()
 {
     return(CreateProduct(SecondProductName, KeyGenerator.GenerateProductKey(SecondProductName)));
 }
Ejemplo n.º 39
0
        private void PEFileKeyGeneratorInternal(bool fileGenerator)
        {
            const string TestBinaryExe = "TestBinaries/HelloWorld.exe";

            using (Stream exe = File.OpenRead(TestBinaryExe))
            {
                var          file      = new SymbolStoreFile(exe, TestBinaryExe);
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new PEFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "helloworld.exe/577f59198000/helloworld.exe");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 1);
                Assert.True(symbolKey.First().Index == "helloworld.pdb/99891b3ed7ae4c3babff8a2b4a9b0c431/helloworld.pdb");

                IEnumerable <SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys);
                Assert.True(clrKeys.Count() == 0);
            }

            const string TestBinaryDll = "TestBinaries/System.Diagnostics.StackTrace.dll";

            using (Stream dll = File.OpenRead(TestBinaryDll))
            {
                var          file      = new SymbolStoreFile(dll, TestBinaryDll);
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new PEFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "system.diagnostics.stacktrace.dll/595cd91b35a00/system.diagnostics.stacktrace.dll");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 2);
                Assert.True(symbolKey.First().Index == "system.diagnostics.stacktrace.ni.pdb/3cd5a68a9f2cd99b169d074e6e956d4fFFFFFFFF/system.diagnostics.stacktrace.ni.pdb");
                Assert.True(symbolKey.Last().Index == "system.diagnostics.stacktrace.pdb/8b2e8cf443144806982ab7d904876a50FFFFFFFF/system.diagnostics.stacktrace.pdb");

                IEnumerable <SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys);
                Assert.True(clrKeys.Count() == 0);
            }

            using (Stream coreclr = TestUtilities.OpenCompressedFile("TestBinaries/coreclr.dll.gz"))
            {
                var          file      = new SymbolStoreFile(coreclr, "coreclr.dll");
                KeyGenerator generator = fileGenerator ? (KeyGenerator) new FileKeyGenerator(_tracer, file) : new PEFileKeyGenerator(_tracer, file);

                IEnumerable <SymbolStoreKey> identityKey = generator.GetKeys(KeyTypeFlags.IdentityKey);
                Assert.True(identityKey.Count() == 1);
                Assert.True(identityKey.First().Index == "coreclr.dll/595ebcd5538000/coreclr.dll");

                IEnumerable <SymbolStoreKey> symbolKey = generator.GetKeys(KeyTypeFlags.SymbolKey);
                Assert.True(symbolKey.Count() == 1);
                Assert.True(symbolKey.First().Index == "coreclr.pdb/3f3d5a3258e64ae8b86b31ff776949351/coreclr.pdb");

                Dictionary <string, SymbolStoreKey> clrKeys = generator.GetKeys(KeyTypeFlags.ClrKeys).ToDictionary((key) => key.Index);
                Assert.True(clrKeys.ContainsKey("mscordaccore.dll/595ebcd5538000/mscordaccore.dll"));
                Assert.True(clrKeys.ContainsKey("mscordbi.dll/595ebcd5538000/mscordbi.dll"));
                Assert.True(clrKeys.ContainsKey("sos.dll/595ebcd5538000/sos.dll"));
                Assert.True(clrKeys.ContainsKey("sos.netcore.dll/595ebcd5538000/sos.netcore.dll"));

                Dictionary <string, SymbolStoreKey> dacdbiKeys = generator.GetKeys(KeyTypeFlags.DacDbiKeys).ToDictionary((key) => key.Index);
                Assert.True(dacdbiKeys.ContainsKey("mscordaccore.dll/595ebcd5538000/mscordaccore.dll"));
                Assert.True(dacdbiKeys.ContainsKey("mscordbi.dll/595ebcd5538000/mscordbi.dll"));
                Assert.False(dacdbiKeys.ContainsKey("sos.dll/595ebcd5538000/sos.dll"));
                Assert.False(dacdbiKeys.ContainsKey("sos.netcore.dll/595ebcd5538000/sos.netcore.dll"));
            }
        }
 public Product GetThirdTestProduct()
 {
     return(CreateProduct(ThirdProductName, KeyGenerator.GenerateProductKey(ThirdProductName)));
 }
Ejemplo n.º 41
0
 public void setUp()
 {
     oaep         = new RSAES_OAEP();
     hash         = new SHA512CryptoServiceProvider();
     keyGenerator = new KeyGenerator();
 }
Ejemplo n.º 42
0
        /// <summary>
        /// 新建员工
        /// </summary>
        /// <param name="employee">员工实体对象</param>
        /// <param name="tran">中间事务对象</param>
        /// <returns>返回处理后的员工实体对象</returns>
        public Employee Add(Employee employee, ICTransaction tran)
        {
            if (employee == null)
            {
                throw new ArgumentNullException("employee");
            }

            employee.EmployeeId = KeyGenerator.GenNewGuidKey();
            StringBuilder query = new StringBuilder();

            query.AppendLine(@"INSERT INTO ");
            query.AppendLine(@"  `Employee` ( ");
            query.AppendLine(@"     `EmployeeId` ");
            query.AppendLine(@"    ,`EmployeeCode` ");
            query.AppendLine(@"    ,`Name` ");
            query.AppendLine(@"    ,`Birthday` ");
            query.AppendLine(@"    ,`Sex` ");
            query.AppendLine(@"    ,`CompanyId` ");
            query.AppendLine(@"    ,`DepartmentId` ");
            query.AppendLine(@"    ,`PositionId` ");
            query.AppendLine(@"    ,`Rand` ");
            query.AppendLine(@"    ,`RVersion` ");
            query.AppendLine(@"    ,`Status` ");
            query.AppendLine(@"    ,`CreaterId` ");
            query.AppendLine(@"    ,`CreateTime` ");
            query.AppendLine(@"    ,`UpdatorId` ");
            query.AppendLine(@"    ,`UpdateTime` ");
            query.AppendLine(@"    ,`StartWorkDate` ");
            query.AppendLine(@"    ,`JoinDate` ");
            query.AppendLine(@"  ) ");
            query.AppendLine(@"VALUES (");
            query.AppendLine(@"     @EmployeeId ");
            query.AppendLine(@"    ,@EmployeeCode ");
            query.AppendLine(@"    ,@Name ");
            query.AppendLine(@"    ,@Birthday ");
            query.AppendLine(@"    ,@Sex ");
            query.AppendLine(@"    ,@CompanyId ");
            query.AppendLine(@"    ,@DepartmentId ");
            query.AppendLine(@"    ,@PositionId ");
            query.AppendLine(@"    ,@Rand ");
            query.AppendLine(@"    ,@RVersion ");
            query.AppendLine(@"    ,@Status ");
            query.AppendLine(@"    ,@CreaterId ");
            query.AppendLine(@"    ,@CreateTime ");
            query.AppendLine(@"    ,@UpdatorId ");
            query.AppendLine(@"    ,@UpdateTime ");
            query.AppendLine(@"    ,@StartWorkDate ");
            query.AppendLine(@"    ,@JoinDate ");
            query.AppendLine(@"); ");

            MySqlParameter[] paramCollection = new MySqlParameter[17];
            paramCollection[0]  = new MySqlParameter("@EmployeeId", MySqlDbType.String, 40);
            paramCollection[1]  = new MySqlParameter("@EmployeeCode", MySqlDbType.String, 15);
            paramCollection[2]  = new MySqlParameter("@Name", MySqlDbType.String, 50);
            paramCollection[3]  = new MySqlParameter("@Birthday", MySqlDbType.DateTime);
            paramCollection[4]  = new MySqlParameter("@Sex", MySqlDbType.Int32);
            paramCollection[5]  = new MySqlParameter("@CompanyId", MySqlDbType.String, 40);
            paramCollection[6]  = new MySqlParameter("@DepartmentId", MySqlDbType.String, 40);
            paramCollection[7]  = new MySqlParameter("@PositionId", MySqlDbType.String, 40);
            paramCollection[8]  = new MySqlParameter("@Rand", MySqlDbType.Int32);
            paramCollection[9]  = new MySqlParameter("@RVersion", MySqlDbType.Int32);
            paramCollection[10] = new MySqlParameter("@Status", MySqlDbType.Int32);
            paramCollection[11] = new MySqlParameter("@CreaterId", MySqlDbType.String, 40);
            paramCollection[12] = new MySqlParameter("@CreateTime", MySqlDbType.DateTime);
            paramCollection[13] = new MySqlParameter("@UpdatorId", MySqlDbType.String, 40);
            paramCollection[14] = new MySqlParameter("@UpdateTime", MySqlDbType.DateTime);
            paramCollection[15] = new MySqlParameter("@StartWorkDate", MySqlDbType.DateTime);
            paramCollection[16] = new MySqlParameter("@JoinDate", MySqlDbType.DateTime);

            paramCollection[0].Value  = employee.EmployeeId;
            paramCollection[1].Value  = employee.EmployeeCode;
            paramCollection[2].Value  = employee.Name;
            paramCollection[3].Value  = employee.Birthday;
            paramCollection[4].Value  = employee.Sex;
            paramCollection[5].Value  = employee.CompanyId;
            paramCollection[6].Value  = employee.DepartmentId;
            paramCollection[7].Value  = employee.PositionId;
            paramCollection[8].Value  = employee.Rand;
            paramCollection[9].Value  = employee.RVersion;
            paramCollection[10].Value = employee.Status;
            paramCollection[11].Value = employee.CreaterId;
            paramCollection[12].Value = employee.CreateTime;
            paramCollection[13].Value = employee.UpdatorId;
            paramCollection[14].Value = employee.UpdateTime;
            paramCollection[15].Value = employee.StartWorkDate;
            paramCollection[16].Value = employee.JoinDate;

            try
            {
                int effectCount = 0;

                if (tran != null)
                {
                    effectCount = MySqlHelper.ExecuteNonQuery((MySqlConnection)tran.Connection, query.ToString(), paramCollection);
                }
                else
                {
                    effectCount = MySqlHelper.ExecuteNonQuery(this.CurrentConnectionString, query.ToString(), paramCollection);
                }

                if (effectCount == 0)
                {
                    employee.EmployeeId = string.Empty;
                    throw new ResponseException((int)ResultCode.NoDataInsert, employee.EmployeeCode);
                }
            }
            catch (Exception ex)
            {
                employee.EmployeeId = string.Empty;
                throw new Exception(ex.Message, ex);
            }

            return(employee);
        }
Ejemplo n.º 43
0
 private void Generate_Click(object sender, RoutedEventArgs e)
 {
     KeyInput.Text = KeyGenerator.Generate();
 }
Ejemplo n.º 44
0
        public void Test_pkv_licence_key_generation_and_verification()
        {
            var pkvLicenceKey = new KeyGenerator();

            var pkvKeyCheck = new KeyCheck();

            var key = string.Empty;

            KeyByteSet[] keyByteSets =
            {
                new KeyByteSet(1,  58,   6,  97),
                new KeyByteSet(2,  96, 254,  23),
                new KeyByteSet(3,  11, 185,  69),
                new KeyByteSet(4,   2,  93,  41),
                new KeyByteSet(5,  62,   4, 234),
                new KeyByteSet(6, 200,  56,  49),
                new KeyByteSet(7,  89,  45, 142),
                new KeyByteSet(8,   6,  88, 32)
            };

            // Change these to a random key byte set from the above array to test key verification with

            var kbs1 = keyByteSets[3];
            var kbs2 = keyByteSets[7];
            var kbs3 = keyByteSets[4];

            // The check project also uses a class called KeyByteSet, but with
            // separate name spacing to achieve single self contained dll

            var keyByteSet1 =
                new KeyByteSet(kbs1.KeyByteNo, kbs1.KeyByteA, kbs1.KeyByteB, kbs1.KeyByteC); // Change no to test others
            var keyByteSet2 = new KeyByteSet(kbs2.KeyByteNo, kbs2.KeyByteA, kbs2.KeyByteB, kbs2.KeyByteC);
            var keyByteSet3 = new KeyByteSet(kbs3.KeyByteNo, kbs3.KeyByteA, kbs3.KeyByteB, kbs3.KeyByteC);

            for (var i = 0; i < 10000; i++)
            {
                var seed = new Random().Next(0, int.MaxValue);

                key = pkvLicenceKey.MakeKey(seed, keyByteSets);

                // Check that check sum validation passes
                Assert.IsTrue(pkvKeyCheck.CheckKeyChecksum(key, keyByteSets.Length));

                // Check using full check method
                Assert.IsTrue(pkvKeyCheck.CheckKey(
                                  key,
                                  new[] { keyByteSet1, keyByteSet2, keyByteSet3 },
                                  keyByteSets.Length,
                                  null
                                  ) == LicenseKeyResult.KeyGood, "Failed on iteration " + i
                              );

                // Check that erroneous check sum validation fails
                Assert.IsFalse(pkvKeyCheck.CheckKeyChecksum(key.Remove(23, 1) + "A",
                                                            keyByteSets.Length)); // Change key by replacing 17th char
            }

            // Check a few random inputs
            Assert.IsFalse(pkvKeyCheck.CheckKey("adcsadrewf",
                                                new[] { keyByteSet1, keyByteSet2 },
                                                keyByteSets.Length,
                                                null) == LicenseKeyResult.KeyGood
                           );
            Assert.IsFalse(pkvKeyCheck.CheckKey("",
                                                new[] { keyByteSet1, keyByteSet2 },
                                                keyByteSets.Length,
                                                null) == LicenseKeyResult.KeyGood
                           );
            Assert.IsFalse(pkvKeyCheck.CheckKey("123",
                                                new[] { keyByteSet1, keyByteSet2 },
                                                keyByteSets.Length,
                                                null) == LicenseKeyResult.KeyGood
                           );
            Assert.IsFalse(pkvKeyCheck.CheckKey("*()",
                                                new[] { keyByteSet1, keyByteSet2 },
                                                keyByteSets.Length,
                                                null) == LicenseKeyResult.KeyGood
                           );
            Assert.IsFalse(pkvKeyCheck.CheckKey("dasdasdasgdjwqidqiwd21887127eqwdaishxckjsabcxjkabskdcbq2e81y12e8712",
                                                new[] { keyByteSet1, keyByteSet2 },
                                                keyByteSets.Length,
                                                null) == LicenseKeyResult.KeyGood
                           );
        }
 public FingerprintEncryption(FingerprintModule fingerprint, string keyId) :
     base(fingerprint, keyId)
 {
     _keyGen = fingerprint.KeyGenerator;
     CreateKey();
 }
Ejemplo n.º 46
0
        ISecretKey GetKey()
        {
            // check to see if we need to get our key from past-versions or newer versions.
            // we want to use symmetric if we are >= 23 or we didn't set it previously.

            useSymmetric = Preferences.Get(useSymmetricPreferenceKey, Platform.HasApiLevel(BuildVersionCodes.M), SecureStorage.Alias);

            // If >= API 23 we can use the KeyStore's symmetric key
            if (useSymmetric && !alwaysUseAsymmetricKey)
            {
                return(GetSymmetricKey());
            }

            // NOTE: KeyStore in < API 23 can only store asymmetric keys
            // specifically, only RSA/ECB/PKCS1Padding
            // So we will wrap our symmetric AES key we just generated
            // with this and save the encrypted/wrapped key out to
            // preferences for future use.
            // ECB should be fine in this case as the AES key should be
            // contained in one block.

            // Get the asymmetric key pair
            var keyPair = GetAsymmetricKeyPair();

            var existingKeyStr = Preferences.Get(prefsMasterKey, null, alias);

            if (!string.IsNullOrEmpty(existingKeyStr))
            {
                try
                {
                    var wrappedKey = Convert.FromBase64String(existingKeyStr);

                    var unwrappedKey = UnwrapKey(wrappedKey, keyPair.Private);
                    var kp           = unwrappedKey.JavaCast <ISecretKey>();

                    return(kp);
                }
                catch (InvalidKeyException ikEx)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Invalid Key. This may be caused by system backup or upgrades. All secure storage items will now be removed. {ikEx.Message}");
                }
                catch (IllegalBlockSizeException ibsEx)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Illegal Block Size. This may be caused by system backup or upgrades. All secure storage items will now be removed. {ibsEx.Message}");
                }
                catch (BadPaddingException paddingEx)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Bad Padding. This may be caused by system backup or upgrades. All secure storage items will now be removed. {paddingEx.Message}");
                }
                SecureStorage.RemoveAll();
            }

            var keyGenerator    = KeyGenerator.GetInstance(aesAlgorithm);
            var defSymmetricKey = keyGenerator.GenerateKey();

            var newWrappedKey = WrapKey(defSymmetricKey, keyPair.Public);

            Preferences.Set(prefsMasterKey, Convert.ToBase64String(newWrappedKey), alias);

            return(defSymmetricKey);
        }
Ejemplo n.º 47
0
        public void BFVKeyGenerationNET()
        {
            var parms = new EncryptionParameters();
            {
                parms.NoiseStandardDeviation = 3.19;
                parms.PolyModulus            = "1x^64 + 1";
                parms.CoeffModulus           = new List <SmallModulus> {
                    DefaultParams.SmallMods60Bit(0)
                };
                parms.PlainModulus = 1 << 6;

                var context = new SEALContext(parms);
                var keygen  = new KeyGenerator(context);

                Assert.IsTrue(keygen.PublicKey.HashBlock.Equals(parms.HashBlock));
                Assert.IsTrue(keygen.SecretKey.HashBlock.Equals(parms.HashBlock));

                var evk = new EvaluationKeys();
                keygen.GenerateEvaluationKeys(60, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(2, evk.Key(2)[0].Size);

                keygen.GenerateEvaluationKeys(30, 1, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(4, evk.Key(2)[0].Size);

                keygen.GenerateEvaluationKeys(2, 2, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(60, evk.Key(2)[0].Size);

                var galks = new GaloisKeys();
                keygen.GenerateGaloisKeys(60, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(2, galks.Key(3)[0].Size);
                Assert.AreEqual(10, galks.Size);

                keygen.GenerateGaloisKeys(30, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(4, galks.Key(3)[0].Size);
                Assert.AreEqual(10, galks.Size);

                keygen.GenerateGaloisKeys(2, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(60, galks.Key(3)[0].Size);
                Assert.AreEqual(10, galks.Size);

                keygen.GenerateGaloisKeys(60, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(127));
                Assert.AreEqual(2, galks.Key(1)[0].Size);
                Assert.AreEqual(2, galks.Key(3)[0].Size);
                Assert.AreEqual(2, galks.Key(5)[0].Size);
                Assert.AreEqual(2, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(127));
                Assert.AreEqual(4, galks.Key(1)[0].Size);
                Assert.AreEqual(4, galks.Key(3)[0].Size);
                Assert.AreEqual(4, galks.Key(5)[0].Size);
                Assert.AreEqual(4, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(2, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(127));
                Assert.AreEqual(60, galks.Key(1)[0].Size);
                Assert.AreEqual(60, galks.Key(3)[0].Size);
                Assert.AreEqual(60, galks.Key(5)[0].Size);
                Assert.AreEqual(60, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    1
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsFalse(galks.HasKey(3));
                Assert.IsFalse(galks.HasKey(127));
                Assert.AreEqual(4, galks.Key(1)[0].Size);
                Assert.AreEqual(1, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    127
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsFalse(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(127));
                Assert.AreEqual(4, galks.Key(127)[0].Size);
                Assert.AreEqual(1, galks.Size);
            }
            {
                parms.NoiseStandardDeviation = 3.19;
                parms.PolyModulus            = "1x^256 + 1";
                parms.CoeffModulus           = new List <SmallModulus> {
                    DefaultParams.SmallMods60Bit(0), DefaultParams.SmallMods30Bit(0), DefaultParams.SmallMods30Bit(1)
                };
                parms.PlainModulus = 1 << 6;

                var context = new SEALContext(parms);
                var keygen  = new KeyGenerator(context);

                Assert.AreEqual(keygen.PublicKey.HashBlock, parms.HashBlock);
                Assert.AreEqual(keygen.SecretKey.HashBlock, parms.HashBlock);

                var evk = new EvaluationKeys();
                keygen.GenerateEvaluationKeys(60, 2, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(2, evk.Key(2)[0].Size);

                keygen.GenerateEvaluationKeys(30, 2, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(4, evk.Key(2)[0].Size);

                keygen.GenerateEvaluationKeys(4, 1, evk);
                Assert.AreEqual(evk.HashBlock, parms.HashBlock);
                Assert.AreEqual(30, evk.Key(2)[0].Size);

                var galks = new GaloisKeys();
                keygen.GenerateGaloisKeys(60, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(2, galks.Key(3)[0].Size);
                Assert.AreEqual(14, galks.Size);

                keygen.GenerateGaloisKeys(30, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(4, galks.Key(3)[0].Size);
                Assert.AreEqual(14, galks.Size);

                keygen.GenerateGaloisKeys(2, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.AreEqual(60, galks.Key(3)[0].Size);
                Assert.AreEqual(14, galks.Size);

                keygen.GenerateGaloisKeys(60, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(511));
                Assert.AreEqual(2, galks.Key(1)[0].Size);
                Assert.AreEqual(2, galks.Key(3)[0].Size);
                Assert.AreEqual(2, galks.Key(5)[0].Size);
                Assert.AreEqual(2, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(511));
                Assert.AreEqual(4, galks.Key(1)[0].Size);
                Assert.AreEqual(4, galks.Key(3)[0].Size);
                Assert.AreEqual(4, galks.Key(5)[0].Size);
                Assert.AreEqual(4, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(2, new List <UInt64> {
                    1, 3, 5, 7
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(3));
                Assert.IsTrue(galks.HasKey(5));
                Assert.IsTrue(galks.HasKey(7));
                Assert.IsFalse(galks.HasKey(9));
                Assert.IsFalse(galks.HasKey(511));
                Assert.AreEqual(60, galks.Key(1)[0].Size);
                Assert.AreEqual(60, galks.Key(3)[0].Size);
                Assert.AreEqual(60, galks.Key(5)[0].Size);
                Assert.AreEqual(60, galks.Key(7)[0].Size);
                Assert.AreEqual(4, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    1
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsTrue(galks.HasKey(1));
                Assert.IsFalse(galks.HasKey(3));
                Assert.IsFalse(galks.HasKey(511));
                Assert.AreEqual(4, galks.Key(1)[0].Size);
                Assert.AreEqual(1, galks.Size);

                keygen.GenerateGaloisKeys(30, new List <UInt64> {
                    511
                }, galks);
                Assert.AreEqual(galks.HashBlock, parms.HashBlock);
                Assert.IsFalse(galks.HasKey(1));
                Assert.IsTrue(galks.HasKey(511));
                Assert.AreEqual(4, galks.Key(511)[0].Size);
                Assert.AreEqual(1, galks.Size);
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Create a single use key file using automatic key material generation.
        /// <para>The Key, and optional IV and IKM are generated automatically using the cipher description contained in the <see cref="CipherDescription"/>.
        /// This overload creates keying material using the seed and digest engines specified with the <see cref="KeyGenerator"/> class</para>
        /// </summary>
        /// 
        /// <param name="Description">The <see cref="CipherDescription">Cipher Description</see> containing the cipher implementation details</param>
        /// <param name="SeedEngine">The <see cref="Prngs">Random Generator</see> used to create the stage I seed material during key generation.</param>
        /// <param name="HashEngine">The <see cref="Digests">Digest Engine</see> used in the stage II phase of key generation.</param>
        /// 
        /// <exception cref="System.ArgumentNullException">Thrown if a KeyParams member is null, but specified in the Header</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if a Header parameter does not match a KeyParams value</exception>
        public void Create(CipherDescription Description, Prngs SeedEngine = Prngs.CSPRng, Digests HashEngine = VTDev.Libraries.CEXEngine.Crypto.Enumeration.Digests.SHA512)
        {
            KeyParams keyParam;

            using (KeyGenerator keyGen = new KeyGenerator(SeedEngine, HashEngine))
                keyParam = keyGen.GetKeyParams(Description.KeySize, Description.IvSize, Description.MacSize);

            Create(Description, keyParam);
        }