예제 #1
0
 internal PublicKeyContext(IConnection connection, PublicKey key)
 {
     _connection = connection;
     Key = key;
     KeyId = key.Id;
     KeyTitle = key.Title;
     KeyData = key.Key;
 }
 public static void Encode(IByteWriter stream, PublicKey encodedPublicKey) {
 XdrEncoding.EncodeInt32((int)encodedPublicKey.Discriminant.InnerValue, stream);
 switch (encodedPublicKey.Discriminant.InnerValue) {
 case CryptoKeyType.CryptoKeyTypeEnum.KEY_TYPE_ED25519:
 Uint256.Encode(stream, encodedPublicKey.Ed25519);
 break;
 }
 }
예제 #3
0
파일: RSA.cs 프로젝트: yakolla/HelloVertX
            public KeyPair()
            {
                // 개인키 생성
                RSAParameters privateParam = System.Security.Cryptography.RSA.Create().ExportParameters(true);

                publicKey = new PublicKey(privateParam.Modulus, privateParam.Exponent);
                privateKey = new PrivateKey(privateParam);
            }
 internal PublicKeychain(PublicKey publicKey, byte[] chainCode, byte[] fingerprint, byte depth, uint child, Network network)
 {
     PublicKey = publicKey;
     ChainCode = chainCode;
     Fingerprint = fingerprint;
     Depth = depth;
     Child = child;
     Network = network;
 }
 public static PublicKey Decode(IByteReader stream) {
   PublicKey decodedPublicKey = new PublicKey();
 decodedPublicKey.Discriminant = CryptoKeyType.Decode(stream);
 switch (decodedPublicKey.Discriminant.InnerValue) {
 case CryptoKeyType.CryptoKeyTypeEnum.KEY_TYPE_ED25519:
 decodedPublicKey.Ed25519 = Uint256.Decode(stream);
 break;
 }
   return decodedPublicKey;
 }
예제 #6
0
        public static PublicKey GeneratePublicKeyFromFile(string fileName)
        {
            PublicKey key = new PublicKey();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            key.Y = GetElement(fs);
            key.G = GetElement(fs);
            key.P = GetElement(fs);

            return key;
        }
예제 #7
0
        public void Initialize()
        {
            MyProcessInfo = new ProcessInfo()
            {
                Status = ProcessInfo.StatusCode.Initializing,
                Type = ProcessInfo.ProcessType.BalloonStore,
                Label = Options.Label
            };

            RegistryEndPoint = new PublicEndPoint(Options.Registry);
            GameManagerEndPoint = new PublicEndPoint(Options.GameManagerEndPoint);

            Identity = new IdentityInfo()
            {
                Alias = Options.Alias,
                ANumber = Options.ANumber,
                FirstName = Options.FirstName,
                LastName = Options.LastName
            };

            SetupCommSubsystem(new BalloonStoreConversationFactory()
            {
                DefaultMaxRetries = Options.Retries,
                DefaultTimeout = Options.Timeout,
                Process = this
            }, minPort: Options.MinPort, maxPort: Options.MaxPort);

            Game = new GameInfo();
            PennyBankPublicKey = new PublicKey();
            WaterSources = new List<GameProcessData>();
            BalloonStores = new List<GameProcessData>();
            UmbrellaSuppliers = new List<GameProcessData>();
            Players = new List<GameProcessData>();
            Balloons = new ResourceSet<Balloon>();
            CachedPennies = new List<Penny>();

            rsa = new RSACryptoServiceProvider();
            rsaSigner = new RSAPKCS1SignatureFormatter(rsa);
            rsaSigner.SetHashAlgorithm("SHA1");
            Hasher = new SHA1Managed();
            RSAParameters parameters = rsa.ExportParameters(false);
            PublicKey = new PublicKey()
            {
                Exponent = parameters.Exponent,
                Modulus = parameters.Modulus
            };

            NextId = 0;
            NumIds = 0;
    }
예제 #8
0
파일: RSA.cs 프로젝트: yakolla/HelloVertX
        static public byte[] Encryption(byte[] data, PublicKey key, bool DoOAEPPadding)
        {
            try
            {
                byte[] encryptedData = null;
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(key);
                    encryptedData = rsa.Encrypt(data, DoOAEPPadding);
                }
                return encryptedData;
            }
            catch (CryptographicException e)
            {
                Debug.Log(e.Message);
            }

            return null;
        }
예제 #9
0
        public static void SaveToFile(string fileName, PublicKey key)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);

            byte[] byte_toWrite = Encoding.ASCII.GetBytes(key.Y.ToString()).ToArray();

            fs.Write(byte_toWrite, 0, byte_toWrite.Count());
            fs.WriteByte((byte)',');

            byte_toWrite = Encoding.ASCII.GetBytes(key.G.ToString()).ToArray();

            fs.Write(byte_toWrite, 0, byte_toWrite.Count());
            fs.WriteByte((byte)',');

            byte_toWrite = Encoding.ASCII.GetBytes(key.P.ToString()).ToArray();

            fs.Write(byte_toWrite, 0, byte_toWrite.Count());
            fs.WriteByte((byte)'\n');
            fs.Close();
        }
예제 #10
0
파일: XRD.cs 프로젝트: AArnott/dotnetxri
        //throws XMLSecurityException
        /**
        * This will verify the XRD against the given public key.  DOM
        * must already be associated with this descriptor.
        * @param oPubKey
        * @throws XMLSecurityException
        */
        public void verifySignature(PublicKey oPubKey)
        {
            if (moElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No DOM stored for XRD");
            }

            // make sure the ID attribute is present
            string sIDAttr = Tags.ATTR_ID_LOW;
            string sIDAttrNS = Tags.NS_XML;
            string sID = moElem.getAttributeNS(sIDAttrNS, sIDAttr);
            if ((sID == null) || (sID.Equals(""))) {
                throw new XMLSecurityException(
                        "Cannot verify the signature. ID is missing for " +
                        moElem.LocalName);
            }
            string sRef = "#" + sID;

            // Set the DOM so that it can be verified
            DOM3Utils.bestEffortSetIDAttr(moElem, sIDAttrNS, sIDAttr);

            XmlElement oAssertionElem =
                DOMUtils.getFirstChildElement(
                        moElem, Tags.NS_SAML, Tags.TAG_ASSERTION);

            if (oAssertionElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No Assertion in XRD");
            }

            XmlElement oSigElem =
                DOMUtils.getFirstChildElement(
                        oAssertionElem, Tags.NS_XMLDSIG, Tags.TAG_SIGNATURE);

            if (oSigElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No signature in Assertion");
            }

            // create the signature element to verify
            XMLSignature oSig = null;
            oSig = new XMLSignature(oSigElem, null);

            // Validate the signature content by checking the references
            string sFailedRef = null;
            SignedInfo oSignedInfo = oSig.getSignedInfo();
            if (oSignedInfo.getLength() != 1) {
                throw new XMLSecurityException(
                        "Cannot verify the signature. Expected 1 reference, got " +
                        oSignedInfo.getLength());
            }

            // make sure it references the correct element
            Reference oRef = oSignedInfo.item(0);
            string sURI = oRef.getURI();
            if (!sRef.Equals(sURI)) {
                throw new XMLSecurityException(
                "Cannot verify the signature. Reference Uri did not match ID");
            }

            // check that the transforms are ok
            bool bEnvelopedFound = false;
            Transforms oTransforms = oRef.getTransforms();
            for (int i = 0; i < oTransforms.getLength(); i++) {
                string sTransform = oTransforms.item(i).getURI();
                if (Transforms.TRANSFORM_ENVELOPED_SIGNATURE.Equals(sTransform)) {
                    // mark that we got the required transform
                    bEnvelopedFound = true;
                } else if (
                        !Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.Equals(
                                sTransform)) {
                    // bonk if we don't have one of the two acceptable transforms
                    throw new XMLSecurityException(
                    "Unexpected transform in signature");
                }
            }

            if (!bEnvelopedFound) {
                throw new XMLSecurityException(
                        "Could not find expected " +
                        Transforms.TRANSFORM_ENVELOPED_SIGNATURE +
                " transform in signature");
            }

            // finally check the signature
            if (!oSig.checkSignatureValue(oPubKey)) {
                throw new RuntimeException("Signature failed to verify.");
            }
        }
예제 #11
0
		public override void Reset () 
		{
			_cert = null;
			_archived = false;
			_extensions = null;
			_name = String.Empty;
			_serial = null;
			_publicKey = null;
			issuer_name = null;
			subject_name = null;
			signature_algorithm = null;
			base.Reset ();
		}
예제 #12
0
 public bool Init(string pubHex)
 {
     return(Base16.TryDecode(pubHex, out pubBa) && PublicKey.TryRead(pubBa, out _));
 }
 public AccountID(PublicKey AccountID)
 {
   InnerValue = AccountID;
 }
예제 #14
0
 public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
 {
     throw new NotImplementedException();
 }
 public override BigInteger PostSignCheck(BigInteger signature, PublicKey pubKey)
 {
     return(BigInteger.Min(signature, pubKey.N - signature) + 2);
 }
예제 #16
0
        public static void TestOid_RSA()
        {
            PublicKey pk = GetTestRsaKey();

            Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value);
        }
예제 #17
0
파일: Player.cs 프로젝트: drewtorg/MyDSoak
 public override void CleanupSession()
 {
     PotentialGames = new List<GameInfo>();
     Pennies = new ConcurrentStack<Penny>();
     Balloons = new ConcurrentQueue<Balloon>();
     Game = new GameInfo();
     GameData = new GameProcessData();
     PennyBankPublicKey = new PublicKey();
     WaterSources = new List<GameProcessData>();
     BalloonStores = new List<GameProcessData>();
     UmbrellaSuppliers = new List<GameProcessData>();
     OtherPlayers = new List<GameProcessData>();
     Umbrella = null;
     UmbrellaRaised = false;
 }
예제 #18
0
 public void RemoveNode(PublicKey nodeId)
 {
     _pendingChanges = true;
 }
예제 #19
0
        public static void TestPublicKey_Key_ECDH()
        {
            PublicKey pk = GetTestECDHKey();

            Assert.Throws <NotSupportedException>(() => pk.Key);
        }
예제 #20
0
        static private void ExampleCKKSEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / CKKS Encoder");

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

            ulong polyModulusDegree = 8192;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            /*
             * The CKKS scheme allows the scale to be reduced between encrypted computations.
             * This is a fundamental and critical feature that makes CKKS very powerful and
             * flexible. We will discuss it in great detail in `3_Levels.cs' and later in
             * `4_CKKS_Basics.cs'.
             */
        }
예제 #21
0
        /*
         * In `1_BFV_Basics.cs' we showed how to perform a very simple computation using the
         * BFV scheme. The computation was performed modulo the PlainModulus parameter, and
         * utilized only one coefficient from a BFV plaintext polynomial. This approach has
         * two notable problems:
         *
         *  (1) Practical applications typically use integer or real number arithmetic,
         *      not modular arithmetic;
         *  (2) We used only one coefficient of the plaintext polynomial. This is really
         *      wasteful, as the plaintext polynomial is large and will in any case be
         *      encrypted in its entirety.
         *
         * For (1), one may ask why not just increase the PlainModulus parameter until no
         * overflow occurs, and the computations behave as in integer arithmetic. The problem
         * is that increasing PlainModulus increases noise budget consumption, and decreases
         * the initial noise budget too.
         *
         * In these examples we will discuss other ways of laying out data into plaintext
         * elements (encoding) that allow more computations without data type overflow, and
         * can allow the full plaintext polynomial to be utilized.
         */
        private static void ExampleIntegerEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / Integer Encoder");

            /*
             * [IntegerEncoder] (For BFV scheme only)
             *
             * The IntegerEncoder encodes integers to BFV plaintext polynomials as follows.
             * First, a binary expansion of the integer is computed. Next, a polynomial is
             * created with the bits as coefficients. For example, the integer
             *
             *  26 = 2^4 + 2^3 + 2^1
             *
             * is encoded as the polynomial 1x^4 + 1x^3 + 1x^1. Conversely, plaintext
             * polynomials are decoded by evaluating them at x=2. For negative numbers the
             * IntegerEncoder simply stores all coefficients as either 0 or -1, where -1 is
             * represented by the unsigned integer PlainModulus - 1 in memory.
             *
             * Since encrypted computations operate on the polynomials rather than on the
             * encoded integers themselves, the polynomial coefficients will grow in the
             * course of such computations. For example, computing the sum of the encrypted
             * encoded integer 26 with itself will result in an encrypted polynomial with
             * larger coefficients: 2x^4 + 2x^3 + 2x^1. Squaring the encrypted encoded
             * integer 26 results also in increased coefficients due to cross-terms, namely,
             *
             *  (1x^4 + 1x^3 + 1x^1)^2 = 1x^8 + 2x^7 + 1x^6 + 2x^5 + 2x^4 + 1x^2;
             *
             * further computations will quickly increase the coefficients much more.
             * Decoding will still work correctly in this case (evaluating the polynomial
             * at x=2), but since the coefficients of plaintext polynomials are really
             * integers modulo plain_modulus, implicit reduction modulo plain_modulus may
             * yield unexpected results. For example, adding 1x^4 + 1x^3 + 1x^1 to itself
             * plain_modulus many times will result in the constant polynomial 0, which is
             * clearly not equal to 26 * plain_modulus. It can be difficult to predict when
             * such overflow will take place especially when computing several sequential
             * multiplications.
             *
             * The IntegerEncoder is easy to understand and use for simple computations,
             * and can be a good tool to experiment with for users new to Microsoft SEAL.
             * However, advanced users will probably prefer more efficient approaches,
             * such as the BatchEncoder or the CKKSEncoder.
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 4096;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);

            /*
             * There is no hidden logic behind our choice of the plain_modulus. The only
             * thing that matters is that the plaintext polynomial coefficients will not
             * exceed this value at any point during our computation; otherwise the result
             * will be incorrect.
             */
            parms.PlainModulus        = new Modulus(512);
            using SEALContext context = new SEALContext(parms);
            Utilities.PrintParameters(context);
            Console.WriteLine();

            using KeyGenerator keygen = new KeyGenerator(context);
            using PublicKey publicKey = keygen.PublicKey;
            using SecretKey secretKey = keygen.SecretKey;
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Evaluator evaluator = new Evaluator(context);
            using Decryptor decryptor = new Decryptor(context, secretKey);

            /*
             * We create an IntegerEncoder.
             */
            using IntegerEncoder encoder = new IntegerEncoder(context);

            /*
             * First, we encode two integers as plaintext polynomials. Note that encoding
             * is not encryption: at this point nothing is encrypted.
             */
            int value1 = 5;

            using Plaintext plain1 = encoder.Encode(value1);
            Utilities.PrintLine();
            Console.WriteLine($"Encode {value1} as polynomial {plain1} (plain1),");

            int value2 = -7;

            using Plaintext plain2 = encoder.Encode(value2);
            Console.WriteLine(new string(' ', 13)
                              + $"Encode {value2} as polynomial {plain2} (plain2),");

            /*
             * Now we can encrypt the plaintext polynomials.
             */
            using Ciphertext encrypted1 = new Ciphertext();
            using Ciphertext encrypted2 = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Encrypt plain1 to encrypted1 and plain2 to encrypted2.");
            encryptor.Encrypt(plain1, encrypted1);
            encryptor.Encrypt(plain2, encrypted2);
            Console.WriteLine("    + Noise budget in encrypted1: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted1));
            Console.WriteLine("    + Noise budget in encrypted2: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted2));

            /*
             * As a simple example, we compute (-encrypted1 + encrypted2) * encrypted2.
             */
            using Ciphertext encryptedResult = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Compute encrypted_result = (-encrypted1 + encrypted2) * encrypted2.");
            evaluator.Negate(encrypted1, encryptedResult);
            evaluator.AddInplace(encryptedResult, encrypted2);
            evaluator.MultiplyInplace(encryptedResult, encrypted2);
            Console.WriteLine("    + Noise budget in encryptedResult: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedResult));

            using Plaintext plainResult = new Plaintext();
            Utilities.PrintLine();
            Console.WriteLine("Decrypt encrypted_result to plain_result.");
            decryptor.Decrypt(encryptedResult, plainResult);

            /*
             * Print the result plaintext polynomial. The coefficients are not even close
             * to exceeding our plainModulus, 512.
             */
            Console.WriteLine($"    + Plaintext polynomial: {plainResult}");

            /*
             * Decode to obtain an integer result.
             */
            Utilities.PrintLine();
            Console.WriteLine("Decode plain_result.");
            Console.WriteLine("    + Decoded integer: {0} ...... Correct.",
                              encoder.DecodeInt32(plainResult));
        }
예제 #22
0
        private static void ExampleBatchEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / Batch Encoder");

            /*
             * [BatchEncoder] (For BFV scheme only)
             *
             * Let N denote the PolyModulusDegree and T denote the PlainModulus. Batching
             * allows the BFV plaintext polynomials to be viewed as 2-by-(N/2) matrices, with
             * each element an integer modulo T. In the matrix view, encrypted operations act
             * element-wise on encrypted matrices, allowing the user to obtain speeds-ups of
             * several orders of magnitude in fully vectorizable computations. Thus, in all
             * but the simplest computations, batching should be the preferred method to use
             * with BFV, and when used properly will result in implementations outperforming
             * anything done with the IntegerEncoder.
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 8192;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);

            /*
             * To enable batching, we need to set the plain_modulus to be a prime number
             * congruent to 1 modulo 2*PolyModulusDegree. Microsoft SEAL provides a helper
             * method for finding such a prime. In this example we create a 20-bit prime
             * that supports batching.
             */
            parms.PlainModulus = PlainModulus.Batching(polyModulusDegree, 20);

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

            /*
             * We can verify that batching is indeed enabled by looking at the encryption
             * parameter qualifiers created by SEALContext.
             */
            using var qualifiers = context.FirstContextData.Qualifiers;
            Console.WriteLine($"Batching enabled: {qualifiers.UsingBatching}");

            using KeyGenerator keygen = new KeyGenerator(context);
            using PublicKey publicKey = keygen.PublicKey;
            using SecretKey secretKey = keygen.SecretKey;
            using RelinKeys relinKeys = keygen.RelinKeysLocal();
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Evaluator evaluator = new Evaluator(context);
            using Decryptor decryptor = new Decryptor(context, secretKey);

            /*
             * Batching is done through an instance of the BatchEncoder class.
             */
            using BatchEncoder batchEncoder = new BatchEncoder(context);

            /*
             * The total number of batching `slots' equals the PolyModulusDegree, N, and
             * these slots are organized into 2-by-(N/2) matrices that can be encrypted and
             * computed on. Each slot contains an integer modulo PlainModulus.
             */
            ulong slotCount = batchEncoder.SlotCount;
            ulong rowSize   = slotCount / 2;

            Console.WriteLine($"Plaintext matrix row size: {rowSize}");

            /*
             * The matrix plaintext is simply given to BatchEncoder as a flattened vector
             * of numbers. The first `rowSize' many numbers form the first row, and the
             * rest form the second row. Here we create the following matrix:
             *
             *  [ 0,  1,  2,  3,  0,  0, ...,  0 ]
             *  [ 4,  5,  6,  7,  0,  0, ...,  0 ]
             */
            ulong[] podMatrix = new ulong[slotCount];
            podMatrix[0]           = 0;
            podMatrix[1]           = 1;
            podMatrix[2]           = 2;
            podMatrix[3]           = 3;
            podMatrix[rowSize]     = 4;
            podMatrix[rowSize + 1] = 5;
            podMatrix[rowSize + 2] = 6;
            podMatrix[rowSize + 3] = 7;

            Console.WriteLine("Input plaintext matrix:");
            Utilities.PrintMatrix(podMatrix, (int)rowSize);

            /*
             * First we use BatchEncoder to encode the matrix into a plaintext polynomial.
             */
            using Plaintext plainMatrix = new Plaintext();
            Utilities.PrintLine();
            Console.WriteLine("Encode plaintext matrix:");
            batchEncoder.Encode(podMatrix, plainMatrix);

            /*
             * We can instantly decode to verify correctness of the encoding. Note that no
             * encryption or decryption has yet taken place.
             */
            List <ulong> podResult = new List <ulong>();

            Console.WriteLine("    + Decode plaintext matrix ...... Correct.");
            batchEncoder.Decode(plainMatrix, podResult);
            Utilities.PrintMatrix(podResult, (int)rowSize);

            /*
             * Next we encrypt the encoded plaintext.
             */
            using Ciphertext encryptedMatrix = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Encrypt plainMatrix to encryptedMatrix.");
            encryptor.Encrypt(plainMatrix, encryptedMatrix);
            Console.WriteLine("    + Noise budget in encryptedMatrix: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedMatrix));

            /*
             * Operating on the ciphertext results in homomorphic operations being performed
             * simultaneously in all 8192 slots (matrix elements). To illustrate this, we
             * form another plaintext matrix
             *
             *  [ 1,  2,  1,  2,  1,  2, ..., 2 ]
             *  [ 1,  2,  1,  2,  1,  2, ..., 2 ]
             *
             * and encode it into a plaintext.
             */
            ulong[] podMatrix2 = new ulong[slotCount];
            for (ulong i = 0; i < slotCount; i++)
            {
                podMatrix2[i] = (i & 1) + 1;
            }
            using Plaintext plainMatrix2 = new Plaintext();
            batchEncoder.Encode(podMatrix2, plainMatrix2);
            Console.WriteLine();
            Console.WriteLine("Second input plaintext matrix:");
            Utilities.PrintMatrix(podMatrix2, (int)rowSize);

            /*
             * We now add the second (plaintext) matrix to the encrypted matrix, and square
             * the sum.
             */
            Utilities.PrintLine();
            Console.WriteLine("Sum, square, and relinearize.");
            evaluator.AddPlainInplace(encryptedMatrix, plainMatrix2);
            evaluator.SquareInplace(encryptedMatrix);
            evaluator.RelinearizeInplace(encryptedMatrix, relinKeys);

            /*
             * How much noise budget do we have left?
             */
            Console.WriteLine("    + Noise budget in result: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedMatrix));

            /*
             * We decrypt and decompose the plaintext to recover the result as a matrix.
             */
            using Plaintext plainResult = new Plaintext();
            Utilities.PrintLine();
            Console.WriteLine("Decrypt and decode result.");
            decryptor.Decrypt(encryptedMatrix, plainResult);
            batchEncoder.Decode(plainResult, podResult);
            Console.WriteLine("    + Result plaintext matrix ...... Correct.");
            Utilities.PrintMatrix(podResult, (int)rowSize);

            /*
             * Batching allows us to efficiently use the full plaintext polynomial when the
             * desired encrypted computation is highly parallelizable. However, it has not
             * solved the other problem mentioned in the beginning of this file: each slot
             * holds only an integer modulo plain_modulus, and unless plain_modulus is very
             * large, we can quickly encounter data type overflow and get unexpected results
             * when integer computations are desired. Note that overflow cannot be detected
             * in encrypted form. The CKKS scheme (and the CKKSEncoder) addresses the data
             * type overflow issue, but at the cost of yielding only approximate results.
             */
        }
예제 #23
0
        public void MemoEncryptDecrypt()
        {
            string message = "6不6"; // including special charactors
            var    result  = AES.EncryptWithChecksum(PrivateKey.FromWif("5J7Yu8zZD5oV9Ex7npmsT3XBbpSdPZPBKBzLLQnXz5JHQVQVfNT"), PublicKey.FromString("GXC8H1wXTAUWcTtogBmA5EW8TUWLA6T1kAXwMKYtnNuqAe1VCXFD9"), 16087047636745223546L, message);
            var    msg     = Hex.BytesToHex(result);

            Console.WriteLine(Hex.BytesToHex(result));
            string decryptedMsg = AES.DecryptWithChecksum(PrivateKey.FromWif("5J7Yu8zZD5oV9Ex7npmsT3XBbpSdPZPBKBzLLQnXz5JHQVQVfNT"), PublicKey.FromString("GXC8H1wXTAUWcTtogBmA5EW8TUWLA6T1kAXwMKYtnNuqAe1VCXFD9"), 16087047636745223546L, Hex.HexToBytes(msg));

            Console.WriteLine(decryptedMsg);
            Assert.AreEqual(message, decryptedMsg);
        }
예제 #24
0
        public static void TestOid_DSA()
        {
            PublicKey pk = GetTestDsaKey();

            Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value);
        }
예제 #25
0
		public abstract void InitVerify (PublicKey key);
예제 #26
0
 public static void CreateFromSubjectPublicKeyInfo_BadEncoding()
 {
     Assert.Throws <CryptographicException>(() =>
                                            PublicKey.CreateFromSubjectPublicKeyInfo(new byte[] { 0xFF }, out _));
 }
예제 #27
0
 public virtual IEnumerable<PublicKey> RemoveKey(PublicKey publicKey)
 {
     Validation.ValidateArgument(publicKey, "publicKey");
     return RemoveKey(publicKey.Id);
 }
예제 #28
0
        public static void TestOid_ECDH()
        {
            PublicKey pk = GetTestECDHKey();

            Assert.Equal("1.2.840.10045.2.1", pk.Oid.Value);
        }
 public X509SubjectKeyIdentifierExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical);
예제 #30
0
파일: RSA.cs 프로젝트: kamasylvia/MyLibrary
 /// <summary>
 /// E(x) = x^b mod n
 /// </summary>
 /// <param name="plaintext"></param>
 /// <returns></returns>
 public override string Encryption(string plaintext, int start = 0) =>
 new String(plaintext.ToCharArray().Select(x => Convert.ToChar(
                                               BigInteger.ModPow(x - start, PublicKey.ElementAt(1), PublicKey.ElementAt(0))
                                               )).ToArray());
예제 #31
0
 /// <exception cref="ArgumentNullException">key is null</exception>
 public RsaCipher(PublicKey key)
 {
     Checker.CheckNull(key);
     degree = key.E.ToBits();
     n      = key.N;
 }
예제 #32
0
파일: RSA.cs 프로젝트: kamasylvia/MyLibrary
 /// <summary>
 /// D(y) = y^a mod n
 /// </summary>
 /// <param name="ciphertext"></param>
 /// <returns></returns>
 public override string Decryption(string ciphertext, int start = 0) =>
 new String(ciphertext.ToCharArray().Select(y => Convert.ToChar(
                                                start + BigInteger.ModPow(y - start, PrivateKey.ElementAt(2), PublicKey.ElementAt(0))
                                                )).ToArray());
        public static bool VerifySignatureWithPublicKey(byte[] hash, string signatureHex, byte[] publicKey)
        {
            var key = new PublicKey(publicKey, Globals.ProdDumpKeyVersion);

            return(key.VerifySignature(hash, signatureHex));
        }
예제 #34
0
 public override string ToString()
 {
     return($"P:{PublicKey.ToString().Substring(0, 12)} A:{Amount}");
 }
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            lblAddressHeader.Visible = false;
            lblAddressItself.Visible = false;
            lblResult.Visible = false;

            // check for null entry
            if (txtPassphrase.Text == "") {
                MessageBox.Show("Passphrase is required.", "Passphrase required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (txtConfCode.Text == "") {
                MessageBox.Show("Confirmation code is required.", "Confirmation code required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Parse confirmation code.
            byte[] confbytes = Bitcoin.Base58CheckToByteArray(txtConfCode.Text.Trim());
            if (confbytes == null) {
                // is it even close?
                if (txtConfCode.Text.StartsWith("cfrm38")) {
                    MessageBox.Show("This is not a valid confirmation code.  It has the right prefix, but " +
                        "doesn't contain valid confirmation data.  Possible typo or incomplete?",
                        "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                MessageBox.Show("This is not a valid confirmation code.", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (confbytes.Length != 51 || confbytes[0] != 0x64 || confbytes[1] != 0x3B || confbytes[2] != 0xF6 ||
                confbytes[3] != 0xA8 || confbytes[4] != 0x9A || confbytes[18] < 0x02 || confbytes[18] > 0x03) {

                // Unrecognized Base58 object.  Do we know what this is?  Tell the user.
                object result = StringInterpreter.Interpret(txtConfCode.Text.Trim());
                if (result != null) {

                    // did we actually get an encrypted private key?  if so, just try to decrypt it.
                    if (result is PassphraseKeyPair) {
                        PassphraseKeyPair ppkp = result as PassphraseKeyPair;
                        if (ppkp.DecryptWithPassphrase(txtPassphrase.Text)) {
                            confirmIsValid(ppkp.GetAddress().AddressBase58);
                            MessageBox.Show("What you provided contains a private key, not just a confirmation. " +
                                "Confirmation is successful, and with this correct passphrase, " +
                                "you are also able to spend the funds from the address.", "This is actually a private key",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        } else {
                            MessageBox.Show("This is not a valid confirmation code.  It looks like an " +
                                "encrypted private key.  Decryption was attempted but the passphrase couldn't decrypt it", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                    }

                    string objectKind = result.GetType().Name;
                    if (objectKind == "AddressBase") {
                        objectKind = "an Address";
                    } else {
                        objectKind = "a " + objectKind;
                    }

                    MessageBox.Show("This is not a valid confirmation code.  Instead, it looks like " + objectKind +
                      ".  Perhaps you entered the wrong thing?  Confirmation codes " +
                    "start with \"cfrm\".", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                MessageBox.Show("This is not a valid confirmation code.", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;

            }

            // extract ownersalt and get an intermediate
            byte[] ownersalt = new byte[8];
            Array.Copy(confbytes, 10, ownersalt, 0, 8);

            Bip38Intermediate intermediate = new Bip38Intermediate(txtPassphrase.Text, ownersalt);

            // derive the 64 bytes we need
            // get ECPoint from passpoint
            PublicKey pk = new PublicKey(intermediate.passpoint);

            byte[] addresshashplusownersalt = new byte[12];
            Array.Copy(confbytes, 6, addresshashplusownersalt, 0, 4);
            Array.Copy(intermediate.ownersalt, 0, addresshashplusownersalt, 4, 8);

            // derive encryption key material
            byte[] derived = new byte[64];
            SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownersalt, 1024, 1, 1, 1, derived);

            byte[] derivedhalf2 = new byte[32];
            Array.Copy(derived, 32, derivedhalf2, 0, 32);

            byte[] unencryptedpubkey = new byte[33];
            // recover the 0x02 or 0x03 prefix
            unencryptedpubkey[0] = (byte)(confbytes[18] ^ (derived[63] & 0x01));

            // decrypt
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform decryptor = aes.CreateDecryptor();

            decryptor.TransformBlock(confbytes, 19, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(confbytes, 19, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(confbytes, 19 + 16, 16, unencryptedpubkey, 17);
            decryptor.TransformBlock(confbytes, 19 + 16, 16, unencryptedpubkey, 17);

            // xor out the padding
            for (int i = 0; i < 32; i++) unencryptedpubkey[i + 1] ^= derived[i];

            // reconstitute the ECPoint
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECPoint point;
            try {
                point = ps.Curve.DecodePoint(unencryptedpubkey);

                // multiply passfactor.  Result is going to be compressed.
                ECPoint pubpoint = point.Multiply(new BigInteger(1, intermediate.passfactor));

                // Do we want it uncompressed?  then we will have to uncompress it.
                byte flagbyte = confbytes[5];
                if ((flagbyte & 0x20) == 0x00) {
                    pubpoint = ps.Curve.CreatePoint(pubpoint.X.ToBigInteger(), pubpoint.Y.ToBigInteger(), false);
                }

                // Convert to bitcoin address and check address hash.
                PublicKey generatedaddress = new PublicKey(pubpoint);

                // get addresshash
                UTF8Encoding utf8 = new UTF8Encoding(false);
                Sha256Digest sha256 = new Sha256Digest();
                byte[] generatedaddressbytes = utf8.GetBytes(generatedaddress.AddressBase58);
                sha256.BlockUpdate(generatedaddressbytes, 0, generatedaddressbytes.Length);
                byte[] addresshashfull = new byte[32];
                sha256.DoFinal(addresshashfull, 0);
                sha256.BlockUpdate(addresshashfull, 0, 32);
                sha256.DoFinal(addresshashfull, 0);

                for (int i = 0; i < 4; i++) {
                    if (addresshashfull[i] != confbytes[i + 6]) {
                        MessageBox.Show("This passphrase is wrong or does not belong to this confirmation code.", "Invalid passphrase", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                confirmIsValid(generatedaddress.AddressBase58);
            } catch {
                // Might throw an exception - not every 256-bit integer is a valid X coordinate
                MessageBox.Show("This passphrase is wrong or does not belong to this confirmation code.", "Invalid passphrase", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
예제 #36
0
파일: Config.cs 프로젝트: smasuda/MinChain
 public bool ShouldSerializePublicKey() => !PublicKey.IsNullOrEmpty();
예제 #37
0
 public PublicKey GeneratePublicKey()
 {
     PublicKey key = new PublicKey();
     key.G = g;
     key.P = p;
     key.Y = BigInteger.ModPow(g, x, p);// modular_pow(g, x, p);
     return key;
 }
예제 #38
0
 public NftItem(ulong collectionId, PublicKey owner, byte[] data)
 {
     CollectionId = collectionId;
     Owner        = owner;
     Data         = data;
 }
 public void ImportPublicKey(string publicKeyString)
 {
     public_key = new PublicKey (publicKeyString);
 }
예제 #40
0
 public NetworkNode(PublicKey publicKey, string ip, int port, long reputation = 0)
 {
     _enode     = new Enode(publicKey, IPAddress.Parse(ip), port);
     Reputation = reputation;
 }
예제 #41
0
파일: KeyPair.cs 프로젝트: daffers/Magnum
 public KeyPair(PublicKey @public, PrivateKey @private)
 {
     Public = @public;
     Private = @private;
 }
예제 #42
0
 public SimpleSyncPeerMock(PublicKey publicKey, string description = "simple mock")
 {
     Node     = new Node(publicKey, "127.0.0.1", 30303, false);
     ClientId = description;
 }
예제 #43
0
		public override void InitVerify (PublicKey key)
		{
			rsa.ImportParameters (((RSAPublicKey)key).Parameters);
		}
예제 #44
0
        public void MemoEncryptDecrypt2()
        {
            string message      = "hi你好"; // including special charactors
            var    msg          = "d504585e9d604bcf24a2ce19c220e5f7";
            string decryptedMsg = AES.DecryptWithChecksum(PrivateKey.FromWif("5J7Yu8zZD5oV9Ex7npmsT3XBbpSdPZPBKBzLLQnXz5JHQVQVfNT"), PublicKey.FromString("GXC8H1wXTAUWcTtogBmA5EW8TUWLA6T1kAXwMKYtnNuqAe1VCXFD9"), 398450244318460L, Hex.HexToBytes(msg));

            Console.WriteLine(decryptedMsg);
            Assert.AreEqual(message, decryptedMsg);
        }
예제 #45
0
 public virtual IEnumerable<PublicKey> AddKey(PublicKey publicKey)
 {
     Validation.ValidateArgument(publicKey, "publicKey");
     return AddKey(publicKey.Title, publicKey.Key);
 }
예제 #46
0
 public PublicKey GeneratePublicKey()
 {
     PublicKey key = new PublicKey();
     key.G = g;
     key.P = p;
     key.Y = modular_pow(g, x, p);
     return key;
 }
        private void btnCombine_Click(object sender, EventArgs e)
        {
            // What is input #1?

            string input1 = txtInput1.Text;
            string input2 = txtInput2.Text;
            PublicKey pub1 = null, pub2 = null;
            KeyPair kp1 = null, kp2 = null;

            if (KeyPair.IsValidPrivateKey(input1)) {
                pub1 = kp1 = new KeyPair(input1);
            } else if (PublicKey.IsValidPublicKey(input1)) {
                pub1 = new PublicKey(input1);
            } else {
                MessageBox.Show("Input key #1 is not a valid Public Key or Private Key Hex", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (KeyPair.IsValidPrivateKey(input2)) {
                pub2 = kp2 = new KeyPair(input2);
            } else if (PublicKey.IsValidPublicKey(input2)) {
                pub2 = new PublicKey(input2);
            } else {
                MessageBox.Show("Input key #2 is not a valid Public Key or Private Key Hex", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (kp1 == null && kp2 == null && rdoAdd.Checked == false) {
                MessageBox.Show("Can't multiply two public keys.  At least one of the keys must be a private key.",
                    "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (pub1.IsCompressedPoint != pub2.IsCompressedPoint) {
                MessageBox.Show("Can't combine a compressed key with an uncompressed key.", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (pub1.AddressBase58 == pub2.AddressBase58) {
                if (MessageBox.Show("Both of the key inputs have the same public key hash.  You can continue, but " +
                   "the results are probably going to be wrong.  You might have provided the wrong " +
                   "information, such as two parts from the same side of the transaction, instead " +
                    "of one part from each side.  Continue anyway?", "Duplicate Key Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) {
                    return;
                }

            }

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");

            // Combining two private keys?
            if (kp1 != null && kp2 != null) {

                BigInteger e1 = new BigInteger(1, kp1.PrivateKeyBytes);
                BigInteger e2 = new BigInteger(1, kp2.PrivateKeyBytes);
                BigInteger ecombined = (rdoAdd.Checked ? e1.Add(e2) : e1.Multiply(e2)).Mod(ps.N);

                System.Diagnostics.Debug.WriteLine(kp1.PublicKeyHex);
                System.Diagnostics.Debug.WriteLine(kp2.PublicKeyHex);
                KeyPair kpcombined = new KeyPair(Util.Force32Bytes(ecombined.ToByteArrayUnsigned()), compressed: kp1.IsCompressedPoint);

                txtOutputAddress.Text = kpcombined.AddressBase58;
                txtOutputPubkey.Text = kpcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = kpcombined.PrivateKeyBase58;

            } else if (kp1 != null || kp2 != null) {
                // Combining one public and one private

                KeyPair priv = (kp1 == null) ? kp2 : kp1;
                PublicKey pub = (kp1 == null) ? pub1 : pub2;

                ECPoint point = pub.GetECPoint();

                ECPoint combined = rdoAdd.Checked ? point.Add(priv.GetECPoint()) : point.Multiply(new BigInteger(1, priv.PrivateKeyBytes));
                ECPoint combinedc = ps.Curve.CreatePoint(combined.X.ToBigInteger(), combined.Y.ToBigInteger(), priv.IsCompressedPoint);
                PublicKey pkcombined = new PublicKey(combinedc.GetEncoded());
                txtOutputAddress.Text = pkcombined.AddressBase58;
                txtOutputPubkey.Text = pkcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = "Only available when combining two private keys";
            } else {
                // Adding two public keys
                ECPoint combined = pub1.GetECPoint().Add(pub2.GetECPoint());
                ECPoint combinedc = ps.Curve.CreatePoint(combined.X.ToBigInteger(), combined.Y.ToBigInteger(), pub1.IsCompressedPoint);
                PublicKey pkcombined = new PublicKey(combinedc.GetEncoded());
                txtOutputAddress.Text = pkcombined.AddressBase58;
                txtOutputPubkey.Text = pkcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = "Only available when combining two private keys";
            }
        }
예제 #48
0
        private byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte[] iv, byte[] ciphertextBody, byte[] macData)
        {
            IIesEngine iesEngine = MakeIesEngine(false, ephemeralPublicKey, privateKey, iv);

            return(iesEngine.ProcessBlock(ciphertextBody, 0, ciphertextBody.Length, macData));
        }
예제 #49
0
 public static void DeleteKey(IConnection connection, PublicKey key)
 {
     if (key != null)
         DeleteKey(connection, key.Id);
 }
예제 #50
0
 /// <summary>
 /// Encrypts data using the provided public key
 /// </summary>
 public Data Encrypt(Data d, PublicKey publicKey)
 {
     _rsa.ImportParameters(publicKey.ToParameters());
     return EncryptPrivate(d);
 }
 public X509SubjectKeyIdentifierExtension(PublicKey key, bool critical);
예제 #52
0
        internal PairSetupReturn HandlePairSetupM5(Tlv parts, ConnectionSession session)
        {
            _logger.LogDebug("Pair Setup Step 5/5");
            _logger.LogDebug("Exchange Response");

            try
            {
                var iOsEncryptedData = parts.GetType(Constants.EncryptedData).AsSpan(); // A
                var zeros            = new byte[] { 0, 0, 0, 0 };
                var nonce            = new Nonce(zeros, Encoding.UTF8.GetBytes("PS-Msg05"));
                var hdkf             = new HkdfSha512();
                var hkdfEncKey       = hdkf.DeriveBytes(
                    SharedSecret.Import(SrpInteger.FromHex(session.ServerSession.Key).ToByteArray()),
                    Encoding.UTF8.GetBytes("Pair-Setup-Encrypt-Salt"),
                    Encoding.UTF8.GetBytes("Pair-Setup-Encrypt-Info"), 32);


                var decrypt = AeadAlgorithm.ChaCha20Poly1305.Decrypt(
                    Key.Import(AeadAlgorithm.ChaCha20Poly1305, hkdfEncKey, KeyBlobFormat.RawSymmetricKey), nonce,
                    new byte[0], iOsEncryptedData, out var output);
                var responseTlv = new Tlv();
                responseTlv.AddType(Constants.State, 6);
                if (!decrypt)
                {
                    responseTlv.AddType(Constants.Error, ErrorCodes.Authentication);
                    return(new PairSetupReturn
                    {
                        State = 5,
                        TlvData = responseTlv,
                        Ok = false
                    });
                }

                var subData = TlvParser.Parse(output);

                byte[] username = subData.GetType(Constants.Identifier);
                byte[] ltpk     = subData.GetType(Constants.PublicKey);
                byte[] proof    = subData.GetType(Constants.Signature);


                var okm = hdkf.DeriveBytes(
                    SharedSecret.Import(SrpInteger.FromHex(session.ServerSession.Key).ToByteArray()),
                    Encoding.UTF8.GetBytes("Pair-Setup-Controller-Sign-Salt"),
                    Encoding.UTF8.GetBytes("Pair-Setup-Controller-Sign-Info"), 32);

                var completeData = okm.Concat(username).Concat(ltpk).ToArray();


                if (!SignatureAlgorithm.Ed25519.Verify(
                        PublicKey.Import(SignatureAlgorithm.Ed25519, ltpk, KeyBlobFormat.RawPublicKey), completeData,
                        proof))
                {
                    var errorTlv = new Tlv();
                    errorTlv.AddType(Constants.Error, ErrorCodes.Authentication);
                    return(new PairSetupReturn
                    {
                        State = 5,
                        TlvData = errorTlv,
                        Ok = false
                    });
                }

                var m5Response = HandlePairSetupM5Raw(session, out var keyPair);
                var plaintext  = TlvParser.Serialize(m5Response);

                _logger.LogDebug($"Decrypted payload {Automatica.Core.Driver.Utility.Utils.ByteArrayToString(plaintext.AsSpan())}");


                var nonce6 = new Nonce(zeros, Encoding.UTF8.GetBytes("PS-Msg06"));

                var encryptedOutput = AeadAlgorithm.ChaCha20Poly1305.Encrypt(
                    Key.Import(AeadAlgorithm.ChaCha20Poly1305, hkdfEncKey, KeyBlobFormat.RawSymmetricKey), nonce6,
                    new byte[0], plaintext);

                responseTlv.AddType(Constants.EncryptedData, encryptedOutput);

                return(new PairSetupReturn
                {
                    State = 5,
                    TlvData = responseTlv,
                    Ok = true,
                    Ltsk = ByteArrayToString(keyPair.PrivateKey),
                    Ltpk = ByteArrayToString(ltpk)
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"{e}, Could not exchange request");
                throw;
            }
        }
예제 #53
0
 public SignatureTool(Ed25519Key key)
 {
     _publicKey = PublicKey.Import(_algorithm, key.ToBytes(), KeyBlobFormat.PkixPublicKey);
 }
예제 #54
0
        public McElieseEllyptic(int n, int k, int d, int t, GaloisField galoisField, MatrixInt scramblerMatrix = null, IList <int> permutation = null, IList <int> mask = null)
        {
            _generator = new ParityCheckMatrixGeneratorEllyptic(2);
            LinearCode = new LinearCode(n, k, d, t, galoisField);

            MatrixInt parityCheckMatrix = null;
            MatrixInt generatorMatrix   = null;

            while (true)
            {
                parityCheckMatrix            = _generator.Generate(LinearCode);
                LinearCode.ParityCheckMatrix = parityCheckMatrix;
                Debug.WriteLine(parityCheckMatrix);

                var minValueFillPercentage = 0.7;

                if (Helper.Weight(parityCheckMatrix) < Math.Ceiling(parityCheckMatrix.RowCount * parityCheckMatrix.ColumnCount * minValueFillPercentage))
                {
                    continue;
                }

                try
                {
                    generatorMatrix = GeneratorMatrixCalculator.CalculateGeneratorMatrixAlt(LinearCode);
                    Debug.WriteLine(generatorMatrix);
                }
                catch (LinearCodeException ex)
                {
                    Debug.WriteLine(ex.Message);
                    continue;
                }

                if (IsGeneratorMatrixValid(parityCheckMatrix, generatorMatrix, galoisField))
                {
                    LinearCode.GeneratorMatrix = generatorMatrix;
                    break;
                }
            }
            if (scramblerMatrix is null)
            {
                scramblerMatrix = Helper.GenerateScramblerMatrix(LinearCode.K);
                while (true)
                {
                    try
                    {
                        MatrixAlgorithms.MatrixInverse(scramblerMatrix, galoisField);
                        break;
                    }
                    catch (SolveMatrixException)
                    {
                        Debug.WriteLine("Reattempting to generate scrambler matrix");
                    }
                }
            }
            if (permutation is null)
            {
                permutation = Helper.GeneratePermutaionList(LinearCode.N);
            }
            if (mask is null)
            {
                mask = Helper.GenerateMask(LinearCode.N, LinearCode.GaloisField);
            }
            var inverseMask = new List <int>(LinearCode.N);

            for (int i = 0; i < LinearCode.N; i++)
            {
                inverseMask.Add(LinearCode.GaloisField.GetMultiplicativeInverse(mask[i]));
            }
            PrivateKey = new PrivateKey
            {
                GeneratorMatrix        = LinearCode.GeneratorMatrix,
                ScramblerMatrix        = scramblerMatrix,
                InverseScramblerMatrix = MatrixAlgorithms.MatrixInverse(scramblerMatrix, galoisField),
                Permutation            = permutation,
                InversePermutation     = Helper.InversePermutation(permutation),
                Mask        = mask,
                InverseMask = inverseMask
            };

            var encryptionMatrix = MatrixAlgorithms.DotMultiplication(PrivateKey.ScramblerMatrix, generatorMatrix, LinearCode.GaloisField);

            Debug.WriteLine(encryptionMatrix);
            encryptionMatrix = encryptionMatrix.PermuteColumns(PrivateKey.Permutation);
            Debug.WriteLine(encryptionMatrix);
            for (int col = 0; col < encryptionMatrix.ColumnCount; col++)
            {
                for (int row = 0; row < encryptionMatrix.RowCount; row++)
                {
                    encryptionMatrix[row, col] = LinearCode.GaloisField.MultiplyWords(encryptionMatrix[row, col], PrivateKey.Mask[col]);
                }
            }
            Debug.WriteLine(encryptionMatrix);

            PublicKey = new PublicKey
            {
                EncryptionMatrix = encryptionMatrix,
            };
        }
예제 #55
0
파일: RSA.cs 프로젝트: yakolla/HelloVertX
 static public byte[] Encryption(string data, PublicKey key, bool DoOAEPPadding)
 {
     return Encryption(Encoding.UTF8.GetBytes(data), key, DoOAEPPadding);
 }
예제 #56
0
 public void Initialize(PublicKey masterPublicKey)
 {
 }
예제 #57
0
 /// <summary>
 /// Generates a new public/private key pair as objects
 /// </summary>
 public void GenerateNewKeyset(ref PublicKey publicKey, ref PrivateKey privateKey)
 {
     string PublicKeyXML = null;
     string PrivateKeyXML = null;
     GenerateNewKeyset(ref PublicKeyXML, ref PrivateKeyXML);
     publicKey = new PublicKey(PublicKeyXML);
     privateKey = new PrivateKey(PrivateKeyXML);
 }
예제 #58
0
        public static Message Parse(NetMQMessage raw, bool reply)
        {
            if (raw.FrameCount == 0)
            {
                throw new ArgumentException("Can't parse empty NetMQMessage.");
            }

            // (reply == true)  [type, sign, pubkey, frames...]
            // (reply == false) [identity, type, sign, pubkey, frames...]
            int headerCount = reply ? 3 : 4;
            var type        = (MessageType)raw[headerCount - 3].ConvertToInt32();
            var publicKey   = new PublicKey(raw[headerCount - 2].ToByteArray());

            byte[] signature = raw[headerCount - 1].ToByteArray();

            NetMQFrame[] body = raw.Skip(headerCount).ToArray();

            if (!publicKey.Verify(body.ToByteArray(), signature))
            {
                throw new InvalidMessageException("the message signature is invalid");
            }

            Message message;

            switch (type)
            {
            case MessageType.Ping:
                message = new Ping();
                break;

            case MessageType.Pong:
                message = new Pong();
                break;

            case MessageType.PeerSetDelta:
                message = PeerSetDelta.ParseBody(body);
                break;

            case MessageType.GetBlocks:
                message = GetBlocks.ParseBody(body);
                break;

            case MessageType.Inventory:
                message = Inventory.Parse(body);
                break;

            case MessageType.GetData:
                message = GetData.Parse(body);
                break;

            case MessageType.Block:
                message = Block.Parse(body);
                break;

            default:
                throw new InvalidMessageException(
                          $"Can't determine NetMQMessage. [type: {type}]");
            }

            if (!reply)
            {
                message.Identity = new Address(raw[0].Buffer);
            }

            return(message);
        }
예제 #59
0
 public static byte[] getServerHash(String toencode, PublicKey par1PublicKey, SecretKey par2SecretKey)
 {
     return digest("SHA-1", new byte[][] { Encoding.GetEncoding("iso-8859-1").GetBytes(toencode), par2SecretKey.getEncoded(), par1PublicKey.getEncoded() });
 }
예제 #60
0
 public TransactionBuilder DeliveredBy(PublicKey publicKey)
 {
     TestObject.DeliveredBy = publicKey;
     return(this);
 }