NextBytes() 공개 메소드

public NextBytes ( byte buffer ) : void
buffer byte
리턴 void
예제 #1
0
        public string Encrypt(string data)
        {
            SecureRandom random = new SecureRandom();

            // Generate 256-bits AES key
            byte[] aesKey = new byte[32];
            random.NextBytes(aesKey);

            // Generate Initialization Vector
            byte[] IV = new byte[12];
            random.NextBytes(IV);

            // Apply RSA/None/PKCS1Padding encryption to the AES key
            byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey);

            // Apply AES/CCM/NoPadding encryption to the data
            byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data);

            var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { });
            aesCipher = new CcmBlockCipher(new AesFastEngine());
            aesCipher.Init(true, ccmParameters);

            var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)];
            var res = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0);
            aesCipher.DoFinal(encrypted, res);

            // Merge 'IV' and 'encrypted' to 'result'
            byte[] result = new byte[IV.Length + encrypted.Length];
            System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length);
            System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length);

            // Return encrypted data
            return Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result);
        }
예제 #2
0
        /// <summary>
        /// Default constructor.  Creates a new matched pair of escrow invitation codes.
        /// </summary>
        public EscrowCodeSet()
        {
            SecureRandom sr = new SecureRandom();

            byte[] x = new byte[32];
            byte[] y = new byte[32];
            sr.NextBytes(x);
            sr.NextBytes(y);

            // Force x to be even
            // Force y to be odd
            x[31] &= 0xFE;
            y[31] |= 0x01;

            KeyPair kx = new KeyPair(x, true);
            KeyPair ky = new KeyPair(y, true);

            BigInteger xi = new BigInteger(1, x);
            BigInteger yi = new BigInteger(1, y);

            ECPoint Gx = kx.GetECPoint();
            byte[] bytesGx = Gx.GetEncoded();
            ECPoint Gy = ky.GetECPoint();
            byte[] bytesGy = Gy.GetEncoded();
            ECPoint Gxy = Gx.Multiply(yi);

            byte[] bytesGxy = Gxy.GetEncoded();
            Sha256Digest sha256 = new Sha256Digest();
            byte[] hashGxy = new byte[32];
            sha256.BlockUpdate(bytesGxy, 0, bytesGxy.Length);
            sha256.DoFinal(hashGxy, 0);
            sha256.BlockUpdate(hashGxy, 0, 32);
            sha256.DoFinal(hashGxy, 0);

            int identifier30 = ((hashGxy[0] & 0x3f) << 24) + (hashGxy[1] << 16) + (hashGxy[2] << 8) + hashGxy[3];

            byte[] invitationA = new byte[74];
            byte[] invitationB = new byte[74];

            long headA = headbaseA + (long)identifier30;
            long headB = headbaseB + (long)identifier30;

            // turn headA and headB into bytes
            for (int i = 7; i >= 0; i--) {
                invitationA[i] = (byte)(headA & 0xFF);
                invitationB[i] = (byte)(headB & 0xFF);
                headA >>= 8;
                headB >>= 8;
            }

            Array.Copy(x, 0, invitationA, 8 + 1, 32);
            Array.Copy(y, 0, invitationB, 8 + 1, 32);
            Array.Copy(bytesGy, 0, invitationA, 8 + 1 + 32, 33);
            Array.Copy(bytesGx, 0, invitationB, 8 + 1 + 32, 33);

            EscrowInvitationCodeA = Util.ByteArrayToBase58Check(invitationA);
            EscrowInvitationCodeB = Util.ByteArrayToBase58Check(invitationB);
        }
예제 #3
0
        private void RandomTest(SecureRandom random)
        {
            byte[] key = new byte[16];
            random.NextBytes(key);

            int length = 1 + random.Next(1024);
            byte[] input = new byte[length];
            random.NextBytes(input);

            SipHash mac = new SipHash();
            mac.Init(new KeyParameter(key));

            UpdateMac(mac, input, UPDATE_BYTES);
            long result1 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_FULL);
            long result2 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_MIX);
            long result3 = mac.DoFinal();

            if (result1 != result2 || result1 != result3)
            {
                Fail("Inconsistent results in random test");
            }
        }
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();

			string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
			IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);

			// Note: In Java build, the IV is automatically generated in JCE layer
			int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
			byte[] iv = new byte[ivLength];
			random.NextBytes(iv);

			ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
			keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
        	Asn1OctetString encryptedKey = new DerOctetString(
				keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

			DerSequence seq = new DerSequence(
				new DerObjectIdentifier(keyEncryptionKeyOID),
				new DerOctetString(iv));

			AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
				PkcsObjectIdentifiers.IdAlgPwriKek, seq);

			return new RecipientInfo(new PasswordRecipientInfo(
				keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
		}
        private static void DoTestClientServer(bool fragment)
        {
            SecureRandom secureRandom = new SecureRandom();

            TlsClientProtocol clientProtocol = new TlsClientProtocol(secureRandom);
            TlsServerProtocol serverProtocol = new TlsServerProtocol(secureRandom);

            clientProtocol.Connect(new MockTlsClient(null));
            serverProtocol.Accept(new MockTlsServer());

            // pump handshake
            bool hadDataFromServer = true;
            bool hadDataFromClient = true;
            while (hadDataFromServer || hadDataFromClient)
            {
                hadDataFromServer = PumpData(serverProtocol, clientProtocol, fragment);
                hadDataFromClient = PumpData(clientProtocol, serverProtocol, fragment);
            }

            // send data in both directions
            byte[] data = new byte[1024];
            secureRandom.NextBytes(data);
            WriteAndRead(clientProtocol, serverProtocol, data, fragment);
            WriteAndRead(serverProtocol, clientProtocol, data, fragment);

            // close the connection
            clientProtocol.Close();
            PumpData(clientProtocol, serverProtocol, fragment);
            CheckClosed(serverProtocol);
            CheckClosed(clientProtocol);
        }
예제 #6
0
		public static void Test()
		{
			Console.Out.WriteLine("Begin Example_060.");
			// Create the AES Service
			AESService aes = new AESService();

			string password = "******";
			SecureRandom random = new SecureRandom();
			byte[] salt = new byte[AESService.SALT_SIZE];
			random.NextBytes(salt);

			// Create the AES Key using password and salt.
			aes.GenerateKey(password, salt);

			// Encode and Decode a string then compare to verify they are the same.
			string clear_text = "This is a test";
			byte[] enc_bytes = aes.Encode(UTF8Encoding.UTF8.GetBytes(clear_text));
			byte[] dec_bytes = aes.Decode(enc_bytes);
			string dec_text = UTF8Encoding.UTF8.GetString(dec_bytes);

			/**
			 * Compare the original and decrypted files.
			 */
			if (Compare.SafeEquals(UTF8Encoding.UTF8.GetBytes(clear_text), UTF8Encoding.UTF8.GetBytes(dec_text)))
			{
				Console.Out.WriteLine("Original and Decrypted are the same!");
			}
			else
			{
				Console.Out.WriteLine("Original and Decrypted are NOT the same!");
			}
			Console.Out.WriteLine("End Example_060.");
		}
예제 #7
0
		public static byte[] GenerateEncryptedPreMasterSecret(SecureRandom random,
			RsaKeyParameters rsaServerPublicKey, Stream output)
		{
			/*
			 * Choose a PremasterSecret and send it encrypted to the server
			 */
			byte[] premasterSecret = new byte[48];
			random.NextBytes(premasterSecret);
			TlsUtilities.WriteVersion(premasterSecret, 0);

			Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine());
			encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, random));

			try
			{
				byte[] keData = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length);
                TlsUtilities.WriteOpaque16(keData, output);
			}
			catch (InvalidCipherTextException)
			{
				/*
				* This should never happen, only during decryption.
				*/
				throw new TlsFatalAlert(AlertDescription.internal_error);
			}

			return premasterSecret;
		}
예제 #8
0
		private void MakeSeedAndPayload(out byte[] seed, out byte[] payload)
		{
			var rnd = new SecureRandom();
			var priv = new byte[32];
			rnd.NextBytes(priv);
			payload = MontgomeryCurve25519.GetPublicKey(priv);
            seed = MontgomeryCurve25519.KeyExchange(MY_PUBLIC, priv);
		}
예제 #9
0
        public JObject Encrypt(string key, JObject blob, string adata)
        {
            var result = new JObject();
            var random = new SecureRandom();

            var iv = new byte[32];
            var salt = new byte[8];

            random.NextBytes(salt);
            random.NextBytes(iv);

            try
            {
                byte[] plainBytes = Encoding.UTF8.GetBytes(blob.ToString());
                byte[] adataBytes = Encoding.UTF8.GetBytes(adata);
                byte[] nonce = ComputeNonce(iv, plainBytes);

                KeyParameter keyParam = CreateKey(key, salt, _iter, _ks);
                var ccm = new AeadParameters(keyParam, MacSize(_ts), nonce, adataBytes);

                var aes = new CcmBlockCipher(new AesFastEngine());
                aes.Init(true, ccm);

                var enc = new byte[aes.GetOutputSize(plainBytes.Length)];

                int res = aes.ProcessBytes(plainBytes, 0, plainBytes.Length, enc, 0);

                aes.DoFinal(enc, res);

                result.Add("ct", Base64.ToBase64String(enc));
                result.Add("iv", Base64.ToBase64String(iv));
                result.Add("salt", Base64.ToBase64String(salt));
                result.Add("adata", EncodeAdata(adata));
                result.Add("mode", Mode);
                result.Add("ks", _ks);
                result.Add("iter", _iter);
                result.Add("ts", _ts);

                return result;
            }
            catch (Exception e)
            {
                throw new ApplicationException("Json encryption failed.", e);
            }
        }
        /// <summary>
        /// Create an intermediate from a passphrase or intermediate code
        /// </summary>
        public Bip38Intermediate(string fromstring, Interpretation interpretation)
        {
            if (interpretation == Interpretation.IntermediateCode) {
                createFromCode(fromstring);
            } else {
                _ownersalt = new byte[8];

                // Get 8 random bytes to use as salt
                SecureRandom sr = new SecureRandom();
                sr.NextBytes(_ownersalt);
                createFromPassphrase(fromstring, _ownersalt);
            }
        }
예제 #11
0
        internal AbstractTlsContext(Org.BouncyCastle.Security.SecureRandom secureRandom, Org.BouncyCastle.Crypto.Tls.SecurityParameters securityParameters)
        {
            IDigest digest = TlsUtilities.CreateHash((byte)4);

            byte[] buffer = new byte[digest.GetDigestSize()];
            secureRandom.NextBytes(buffer);
            this.mNonceRandom = new DigestRandomGenerator(digest);
            this.mNonceRandom.AddSeedMaterial(NextCounterValue());
            this.mNonceRandom.AddSeedMaterial(Times.NanoTime());
            this.mNonceRandom.AddSeedMaterial(buffer);
            this.mSecureRandom       = secureRandom;
            this.mSecurityParameters = securityParameters;
        }
       internal AbstractTlsContext(SecureRandom secureRandom, SecurityParameters securityParameters)
        {
            IDigest d = TlsUtilities.CreateHash(HashAlgorithm.sha256);
            byte[] seed = new byte[d.GetDigestSize()];
            secureRandom.NextBytes(seed);

            this.mNonceRandom = new DigestRandomGenerator(d);
            mNonceRandom.AddSeedMaterial(NextCounterValue());
            mNonceRandom.AddSeedMaterial(Times.NanoTime());
            mNonceRandom.AddSeedMaterial(seed);

            this.mSecureRandom = secureRandom;
            this.mSecurityParameters = securityParameters;
        }
        /// <summary>
        /// Create an intermediate from a passphrase or intermediate code
        /// </summary>
        public Bip38Intermediate(string fromstring, Interpretation interpretation, int startingSequenceNumber = 0)
        {
            if (interpretation == Interpretation.IntermediateCode) {
                createFromCode(fromstring);
            } else {
                _ownerentropy = new byte[8];

                // Get 8 random bytes to use as salt
                SecureRandom sr = new SecureRandom();
                sr.NextBytes(_ownerentropy);
                // set lot number between 100000 and 999999, and sequence number to 1
                long x = (sr.NextLong () % 900000L + 100000L) * 4096L + (long)startingSequenceNumber;
                for (int i=7; i>=4; i--) {
                    _ownerentropy[i] = (byte)(x & 0xFF);
                    x >>= 8;
                }
                createFromPassphrase(fromstring, _ownerentropy, true);
            }
        }
예제 #14
0
		public static void Test()
		{
			Console.Out.WriteLine("Begin Example_070.");
			string password = "******";
			string secret_key = "secret-shared-key";
			string content = "Lorem ipsum dolor sit amet, duo cu nobis epicurei hendrerit, mei agam elit an.";

			string hmac = HMAC.Sha256(content, secret_key);
			Console.Out.WriteLine("HMAC_sha256: " + hmac);

			string hex_string = Hex.Encode(UTF8Encoding.UTF8.GetBytes(content));
			Console.Out.WriteLine("Content Hex String: " + hex_string);

			SecureRandom random = new SecureRandom();
			byte[] salt = new byte[AESService.SALT_SIZE];
			random.NextBytes(salt);

			hmac = HMAC.Sha256(content, password);
			Console.Out.WriteLine("HMAC_sha256: " + hmac);
			Console.Out.WriteLine("End Example_070.");
		}
예제 #15
0
        public void TestClientServer()
        {
            SecureRandom secureRandom = new SecureRandom();

            PipedStream clientPipe = new PipedStream();
            PipedStream serverPipe = new PipedStream(clientPipe);

            TlsClientProtocol clientProtocol = new TlsClientProtocol(clientPipe, secureRandom);
            TlsServerProtocol serverProtocol = new TlsServerProtocol(serverPipe, secureRandom);

            Server server = new Server(serverProtocol);

            Thread serverThread = new Thread(new ThreadStart(server.Run));
            serverThread.Start();

            MockSrpTlsClient client = new MockSrpTlsClient(null, MockSrpTlsServer.TEST_IDENTITY, MockSrpTlsServer.TEST_PASSWORD);
            clientProtocol.Connect(client);

            // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity
            int length = 1000;

            byte[] data = new byte[length];
            secureRandom.NextBytes(data);

            Stream output = clientProtocol.Stream;
            output.Write(data, 0, data.Length);

            byte[] echo = new byte[data.Length];
            int count = Streams.ReadFully(clientProtocol.Stream, echo);

            Assert.AreEqual(count, data.Length);
            Assert.IsTrue(Arrays.AreEqual(data, echo));

            output.Close();

            serverThread.Join();
        }
        /// <summary>
        /// Generate a set of M-of-N parts for a specific private key.
        /// If desiredPrivKey is null, then a random key will be selected.
        /// </summary>
        public void Generate(int PartsNeededToDecode, int PartsToGenerate, byte[] desiredPrivKey)
        {
            if (PartsNeededToDecode > PartsToGenerate) {
                throw new ApplicationException("Number of parts needed exceeds number of parts to generate.");
            }

            if (PartsNeededToDecode > 8 || PartsToGenerate > 8) {
                throw new ApplicationException("Maximum number of parts is 8");
            }

            if (PartsNeededToDecode < 1 || PartsToGenerate < 1) {
                throw new ApplicationException("Minimum number of parts is 1");
            }

            if (desiredPrivKey != null && desiredPrivKey.Length != 32) {
                throw new ApplicationException("Desired private key must be 32 bytes");
            }

            KeyParts.Clear();
            decodedKeyParts.Clear();

            SecureRandom sr = new SecureRandom();

            // Get 8 random big integers into v[i].
            byte[][] vvv = new byte[8][];
            BigInteger[] v = new BigInteger[8];

            for (int i = 0; i < 8; i++) {
                byte[] b = new byte[32];
                sr.NextBytes(b, 0, 32);
                // For larger values of i, chop off some most-significant-bits to prevent overflows as they are
                // multiplied with increasingly larger factors.
                if (i >= 7) {
                    b[0] &= 0x7f;
                }
                v[i] = new BigInteger(1, b);
                Debug.WriteLine(String.Format("v({0})={1}", i, v[i].ToString()));

            }

            // if a certain private key is desired, then specify it.
            if (desiredPrivKey != null) {
                // replace v[0] with xor(v[1...7]) xor desiredPrivKey
                BigInteger newv0 = BigInteger.Zero;
                for (int i=1; i<PartsNeededToDecode; i++) {
                    newv0 = newv0.Xor(v[i]);
                }
                v[0] = newv0.Xor(new BigInteger(1,desiredPrivKey));

            }

            // Generate the expected private key from all the parts
            BigInteger privkey = new BigInteger("0");
            for (int i = 0; i < PartsNeededToDecode; i++) {
                privkey = privkey.Xor(v[i]);
            }

            // Get the bitcoin address
            byte[] keybytes = privkey.ToByteArrayUnsigned();
            // make sure we have 32 bytes, we'll need it
            if (keybytes.Length < 32) {
                byte[] array32 = new byte[32];
                Array.Copy(keybytes, 0, array32, 32 - keybytes.Length, keybytes.Length);
                keybytes = array32;
            }
            KeyPair = new KeyPair(keybytes);

            byte[] checksum = Util.ComputeSha256(BitcoinAddress);

            // Generate the parts
            for (int i = 0; i < PartsToGenerate; i++) {
                BigInteger total = new BigInteger("0");
                for (int j = 0; j < PartsNeededToDecode; j++) {

                    int factor = 1;
                    for (int ii = 0; ii <= i; ii++) factor = factor * (j + 1);

                    BigInteger bfactor = new BigInteger(factor.ToString());

                    total = total.Add(v[j].Multiply(bfactor));
                }

                Debug.WriteLine(String.Format(" pc{0}={1}", i, total.ToString()));
                byte[] parts = new byte[39];
                parts[0] = 0x4f;
                parts[1] = (byte)(0x93 + PartsNeededToDecode);
                int parts23 = (((checksum[0] << 8) + checksum[1]) & 0x1ff);
                Debug.WriteLine("checksum " + parts23.ToString());
                parts23 += 0x6000;
                parts23 += (i << 9);
                byte[] btotal = total.ToByteArrayUnsigned();
                for (int jj = 0; jj < btotal.Length; jj++) {
                    parts[jj + 4 + (35 - btotal.Length)] = btotal[jj];
                }

                parts[2] = (byte)((parts23 & 0xFF00) >> 8);
                parts[3] = (byte)(parts23 & 0xFF);

                KeyParts.Add(Util.ByteArrayToBase58Check(parts));
                decodedKeyParts.Add(parts);
            }
        }
예제 #17
0
        public void Save(
            Stream			stream,
            char[]			password,
            SecureRandom	random)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (random == null)
                throw new ArgumentNullException("random");

            //
            // handle the keys
            //
            Asn1EncodableVector keyBags = new Asn1EncodableVector();
            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];

                DerObjectIdentifier bagOid;
                Asn1Encodable bagData;

                if (password == null)
                {
                    bagOid = PkcsObjectIdentifiers.KeyBag;
                    bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
                }
                else
                {
                    bagOid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
                }

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    Asn1Encodable entry = privKey[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry ct = GetCertificate(name);
                    AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
            }

            byte[] keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
            ContentInfo keysInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));

            //
            // certificate processing
            //
            byte[] cSalt = new byte[SaltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector	certBags = new Asn1EncodableVector();
            Pkcs12PbeParams		cParams = new Pkcs12PbeParams(cSalt, MinIterations);
            AlgorithmIdentifier	cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            ISet				doneCerts = new HashSet();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    Asn1Encodable entry = certEntry[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey();
                    SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                    continue;

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        continue;

                    Asn1Encodable entry = cert[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'certId'
                //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(cert.Certificate);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts.Contains(cert.Certificate))
                    continue;

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
            }

            byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();

            ContentInfo certsInfo;
            if (password == null)
            {
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
            }
            else
            {
                byte[] certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
                EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
            }

            ContentInfo[] info = new ContentInfo[]{ keysInfo, certsInfo };

            byte[] data = new AuthenticatedSafe(info).GetEncoded(
                useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));

            //
            // create the mac
            //
            MacData macData = null;
            if (password != null)
            {
                byte[] mSalt = new byte[20];
                random.NextBytes(mSalt);

                byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
                    mSalt, MinIterations, password, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, mac);

                macData = new MacData(dInfo, mSalt, MinIterations);
            }

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, macData);

            DerOutputStream derOut;
            if (useDerEncoding)
            {
                derOut = new DerOutputStream(stream);
            }
            else
            {
                derOut = new BerOutputStream(stream);
            }

            derOut.WriteObject(pfx);
        }
예제 #18
0
파일: Helper.cs 프로젝트: bucknellu/Nyan
 public static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false)
 {
     var Random = new SecureRandom();
     var Salt = new byte[16];
     Random.NextBytes(Salt);
     var Curve = ECNamedCurveTable.GetByName("prime256v1");
     var Spec = new ECDomainParameters(Curve.Curve, Curve.G, Curve.N, Curve.H, Curve.GetSeed());
     var Generator = new ECKeyPairGenerator();
     Generator.Init(new ECKeyGenerationParameters(Spec, new SecureRandom()));
     var KeyPair = Generator.GenerateKeyPair();
     var AgreementGenerator = new ECDHBasicAgreement();
     AgreementGenerator.Init(KeyPair.Private);
     var IKM =
         AgreementGenerator.CalculateAgreement(new ECPublicKeyParameters(Spec.Curve.DecodePoint(userKey), Spec));
     var PRK = GenerateHKDF(userSecret, IKM.ToByteArrayUnsigned(),
         Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
     var PublicKey = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded(false);
     var CEK = GenerateHKDF(Salt, PRK, CreateInfoChunk("aesgcm", userKey, PublicKey), 16);
     var Nonce = GenerateHKDF(Salt, PRK, CreateInfoChunk("nonce", userKey, PublicKey), 12);
     if (randomisePadding && (padding > 0)) padding = Convert.ToUInt16(Math.Abs(Random.NextInt()) % (padding + 1));
     var Input = new byte[padding + 2 + data.Length];
     Buffer.BlockCopy(ConvertInt(padding), 0, Input, 0, 2);
     Buffer.BlockCopy(data, 0, Input, padding + 2, data.Length);
     var Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
     Cipher.Init(true, new AeadParameters(new KeyParameter(CEK), 128, Nonce));
     var Message = new byte[Cipher.GetOutputSize(Input.Length)];
     Cipher.DoFinal(Input, 0, Input.Length, Message, 0);
     return new EncryptionResult { Salt = Salt, Payload = Message, PublicKey = PublicKey };
 }
 public static byte[] GetNextBytes(SecureRandom secureRandom, int length)
 {
     byte[] result = new byte[length];
     secureRandom.NextBytes(result);
     return(result);
 }
예제 #20
0
        public override void PerformTest()
        {
            doTestSig(1, pub1, prv1, slt1a, msg1a, sig1a);
            doTestSig(2, pub1, prv1, slt1b, msg1b, sig1b);
            doTestSig(3, pub2, prv2, slt2a, msg2a, sig2a);
            doTestSig(4, pub2, prv2, slt2b, msg2b, sig2b);
            doTestSig(5, pub4, prv4, slt4a, msg4a, sig4a);
            doTestSig(6, pub4, prv4, slt4b, msg4b, sig4b);
            doTestSig(7, pub8, prv8, slt8a, msg8a, sig8a);
            doTestSig(8, pub8, prv8, slt8b, msg8b, sig8b);
            doTestSig(9, pub9, prv9, slt9a, msg9a, sig9a);
            doTestSig(10, pub9, prv9, slt9b, msg9b, sig9b);

            //
            // loop test - sha-1 only
            //
            PssSigner eng = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);
            int failed = 0;
            byte[] data = new byte[DataLength];

            SecureRandom random = new SecureRandom();
            random.NextBytes(data);

            for (int j = 0; j < NumTests; j++)
            {
                eng.Init(true, new ParametersWithRandom(prv8, random));

                eng.BlockUpdate(data, 0, data.Length);

                byte[] s = eng.GenerateSignature();

                eng.Init(false, pub8);

                eng.BlockUpdate(data, 0, data.Length);

                if (!eng.VerifySignature(s))
                {
                    failed++;
                }
            }

            if (failed != 0)
            {
                Fail("loop test failed - failures: " + failed);
            }

            //
            // loop test - sha-256 and sha-1
            //
            eng = new PssSigner(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), 20);
            failed = 0;
            data = new byte[DataLength];

            random.NextBytes(data);

            for (int j = 0; j < NumTests; j++)
            {
                eng.Init(true, new ParametersWithRandom(prv8, random));

                eng.BlockUpdate(data, 0, data.Length);

                byte[] s = eng.GenerateSignature();

                eng.Init(false, pub8);

                eng.BlockUpdate(data, 0, data.Length);

                if (!eng.VerifySignature(s))
                {
                    failed++;
                }
            }

            if (failed != 0)
            {
                Fail("loop test failed - failures: " + failed);
            }
        }
		private static byte[] CreateIV(
			SecureRandom	random,
			int				ivLength)
		{
			byte[] iv = new byte[ivLength];
			random.NextBytes(iv);
			return iv;
		}
        protected static byte[] CreateRandomBlock(bool useGMTUnixTime, SecureRandom random, string asciiLabel)
        {
            /*
             * We use the TLS 1.0 PRF on the SecureRandom output, to guard against RNGs where the raw
             * output could be used to recover the internal state.
             */
            byte[] secret = new byte[32];
            random.NextBytes(secret);

            byte[] seed = new byte[8];
            // TODO Use high-resolution timer
            TlsUtilities.WriteUint64(DateTimeUtilities.CurrentUnixMs(), seed, 0);

            byte[] result = TlsUtilities.PRF(secret, asciiLabel, seed, 32);

            if (useGMTUnixTime)
            {
                TlsUtilities.WriteGmtUnixTime(result, 0);
            }

            return result;
        }
예제 #23
0
        public void DoTest13()
        {
            BigInteger modulus = new BigInteger(1, Hex.Decode("CDCBDABBF93BE8E8294E32B055256BBD0397735189BF75816341BB0D488D05D627991221DF7D59835C76A4BB4808ADEEB779E7794504E956ADC2A661B46904CDC71337DD29DDDD454124EF79CFDD7BC2C21952573CEFBA485CC38C6BD2428809B5A31A898A6B5648CAA4ED678D9743B589134B7187478996300EDBA16271A861"));
            BigInteger pubExp = new BigInteger(1, Hex.Decode("010001"));
            BigInteger privExp = new BigInteger(1, Hex.Decode("4BA6432AD42C74AA5AFCB6DF60FD57846CBC909489994ABD9C59FE439CC6D23D6DE2F3EA65B8335E796FD7904CA37C248367997257AFBD82B26F1A30525C447A236C65E6ADE43ECAAF7283584B2570FA07B340D9C9380D88EAACFFAEEFE7F472DBC9735C3FF3A3211E8A6BBFD94456B6A33C17A2C4EC18CE6335150548ED126D"));

            RsaKeyParameters pubParams = new RsaKeyParameters(false, modulus, pubExp);
            RsaKeyParameters privParams = new RsaKeyParameters(true, modulus, privExp);

            IAsymmetricBlockCipher rsaEngine = new RsaBlindedEngine();
            IDigest digest = new Sha256Digest();

            // set challenge to all zero's for verification
            byte[] challenge = new byte[8];

            // DOES NOT USE FINAL BOOLEAN TO INDICATE RECOVERY
            Iso9796d2Signer signer = new Iso9796d2Signer(rsaEngine, digest, false);

            // sign
            signer.Init(true, privParams);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            byte[]  sig = signer.GenerateSignature();

            // verify
            signer.Init(false, pubParams);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            if (!signer.VerifySignature(sig))
            {
                Fail("basic verification failed");
            }

            // === LETS ACTUALLY DO SOME RECOVERY, USING INPUT FROM INTERNAL AUTHENTICATE ===

            signer.Reset();

            string args0 = "482E20D1EDDED34359C38F5E7C01203F9D6B2641CDCA5C404D49ADAEDE034C7481D781D043722587761C90468DE69C6585A1E8B9C322F90E1B580EEDAB3F6007D0C366CF92B4DB8B41C8314929DCE2BE889C0129123484D2FD3D12763D2EBFD12AC8E51D7061AFCA1A53DEDEC7B9A617472A78C952CCC72467AE008E5F132994";

            digest = new Sha1Digest();

            signer = new Iso9796d2Signer(rsaEngine, digest, true);


            signer.Init(false, pubParams);
            byte[] signature = Hex.Decode(args0);
            signer.UpdateWithRecoveredMessage(signature);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            if (!signer.VerifySignature(signature))
            {
                Fail("recovered + challenge signature failed");
            }

            // === FINALLY, USING SHA-256 ===

            signer.Reset();

            digest = new Sha256Digest();

            // NOTE setting implicit to false does not actually do anything for verification !!!
            signer = new Iso9796d2Signer(rsaEngine, digest, false);


            signer.Init(true, privParams);
            // generate NONCE of correct length using some inner knowledge
            int nonceLength = modulus.BitLength / 8 - 1 - digest.GetDigestSize() - 2;
            byte[] nonce = new byte[nonceLength];
            SecureRandom rnd = new SecureRandom();

            rnd.NextBytes(nonce);

            signer.BlockUpdate(nonce, 0, nonce.Length);
            signer.BlockUpdate(challenge, 0, challenge.Length);
            byte[] sig3 = signer.GenerateSignature();

            signer.Init(false, pubParams);
            signer.UpdateWithRecoveredMessage(sig3);
            signer.BlockUpdate(challenge, 0, challenge.Length);
            if (signer.VerifySignature(sig3))
            {
                if (signer.HasFullMessage())
                {
                    Fail("signer indicates full message");
                }
                byte[] recoverableMessage = signer.GetRecoveredMessage();

                // sanity check, normally the nonce is ignored in eMRTD specs (PKI Technical Report)
                if (!Arrays.AreEqual(nonce, recoverableMessage))
                {
                    Fail("Nonce compare with recoverable part of message failed");
                }
            }
            else
            {
                Fail("recoverable + nonce failed.");
            }
        }
예제 #24
0
		byte[] EncryptAsymmetricKeyParameter (AsymmetricKeyParameter key)
		{
			var cipher = PbeUtilities.CreateEngine (EncryptionAlgorithm.Id) as IBufferedCipher;
			var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo (key);
			var random = new SecureRandom ();
			var salt = new byte[SaltSize];

			if (cipher == null)
				throw new Exception ("Unknown encryption algorithm: " + EncryptionAlgorithm.Id);

			random.NextBytes (salt);

			var pbeParameters = PbeUtilities.GenerateAlgorithmParameters (EncryptionAlgorithm.Id, salt, MinIterations);
			var algorithm = new AlgorithmIdentifier (EncryptionAlgorithm, pbeParameters);
			var cipherParameters = PbeUtilities.GenerateCipherParameters (algorithm, passwd);

			if (cipherParameters == null)
				throw new Exception ("BouncyCastle bug detected: Failed to generate cipher parameters.");

			cipher.Init (true, cipherParameters);

			var encoded = cipher.DoFinal (keyInfo.GetEncoded ());

			var encrypted = new EncryptedPrivateKeyInfo (algorithm, encoded);

			return encrypted.GetEncoded ();
		}
예제 #25
0
		private bool isProcessingOkay(
			RsaKeyParameters    pub,
			RsaKeyParameters    prv,
			byte[]              data,
			SecureRandom        random)
		{
			RsaBlindingFactorGenerator blindFactorGen = new RsaBlindingFactorGenerator();
			RsaBlindingEngine blindingEngine = new RsaBlindingEngine();
			PssSigner blindSigner = new PssSigner(blindingEngine, new Sha1Digest(), 20);
			PssSigner pssEng = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);

			random.NextBytes(data);

			blindFactorGen.Init(pub);

			BigInteger blindFactor = blindFactorGen.GenerateBlindingFactor();
			RsaBlindingParameters parameters = new RsaBlindingParameters(pub, blindFactor);

			// generate a blind signature
			blindSigner.Init(true, new ParametersWithRandom(parameters, random));

			blindSigner.BlockUpdate(data, 0, data.Length);

			byte[] blindedData = blindSigner.GenerateSignature();

			RsaEngine signerEngine = new RsaEngine();

			signerEngine.Init(true, prv);

			byte[] blindedSig = signerEngine.ProcessBlock(blindedData, 0, blindedData.Length);

			// unblind the signature
			blindingEngine.Init(false, parameters);

			byte[] s = blindingEngine.ProcessBlock(blindedSig, 0, blindedSig.Length);

			//verify signature with PssSigner
			pssEng.Init(false, pub);
			pssEng.BlockUpdate(data, 0, data.Length);

			return pssEng.VerifySignature(s);
		}
예제 #26
0
 private static byte[] CreateIV(SecureRandom random, int ivLength)
 {
     byte[] array = new byte[ivLength];
     random.NextBytes(array);
     return(array);
 }
예제 #27
0
		private void randomTest(
			SecureRandom srng)
		{
			int DAT_LEN = srng.Next(1024);
			byte[] nonce = new byte[NONCE_LEN];
			byte[] authen = new byte[AUTHEN_LEN];
			byte[] datIn = new byte[DAT_LEN];
			byte[] key = new byte[16];
			srng.NextBytes(nonce);
			srng.NextBytes(authen);
			srng.NextBytes(datIn);
			srng.NextBytes(key);

			AesFastEngine engine = new AesFastEngine();
			KeyParameter sessKey = new KeyParameter(key);
			EaxBlockCipher eaxCipher = new EaxBlockCipher(engine);

			AeadParameters parameters = new AeadParameters(sessKey, MAC_LEN * 8, nonce, authen);
			eaxCipher.Init(true, parameters);

			byte[] intrDat = new byte[eaxCipher.GetOutputSize(datIn.Length)];
			int outOff = eaxCipher.ProcessBytes(datIn, 0, DAT_LEN, intrDat, 0);
			outOff += eaxCipher.DoFinal(intrDat, outOff);

			eaxCipher.Init(false, parameters);
			byte[] datOut = new byte[eaxCipher.GetOutputSize(outOff)];
			int resultLen = eaxCipher.ProcessBytes(intrDat, 0, outOff, datOut, 0);
			eaxCipher.DoFinal(datOut, resultLen);

			if (!AreEqual(datIn, datOut))
			{
				Fail("EAX roundtrip failed to match");
			}
		}
예제 #28
0
 // Token: 0x06000089 RID: 137 RVA: 0x00007028 File Offset: 0x00005228
 public static byte[] GetNextBytes(SecureRandom secureRandom, int length)
 {
     byte[] array = new byte[length];
     secureRandom.NextBytes(array);
     return(array);
 }
예제 #29
0
//		private string GetHexEncoded(byte[] bytes)
//		{
//			bytes = Hex.Encode(bytes);
//
//			char[] chars = new char[bytes.Length];
//
//			for (int i = 0; i != bytes.Length; i++)
//			{
//				chars[i] = (char)bytes[i];
//			}
//
//			return new string(chars);
//		}

		private PemObject CreatePemObject(
			object			obj,
			string			algorithm,
			char[]			password,
			SecureRandom	random)
		{
			if (obj == null)
				throw new ArgumentNullException("obj");
			if (algorithm == null)
				throw new ArgumentNullException("algorithm");
			if (password == null)
				throw new ArgumentNullException("password");
			if (random == null)
				throw new ArgumentNullException("random");

			if (obj is AsymmetricCipherKeyPair)
			{
				return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random);
			}

			string type = null;
			byte[] keyData = null;

			if (obj is AsymmetricKeyParameter)
			{
				AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
				if (akp.IsPrivate)
				{
					string keyType;
					keyData = EncodePrivateKey(akp, out keyType);

					type = keyType + " PRIVATE KEY";
				}
			}

			if (type == null || keyData == null)
			{
				// TODO Support other types?
				throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName);
			}


			string dekAlgName = algorithm.ToUpper(CultureInfo.InvariantCulture);

			// Note: For backward compatibility
			if (dekAlgName == "DESEDE")
			{
				dekAlgName = "DES-EDE3-CBC";
			}

			int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8;

			byte[] iv = new byte[ivLength];
			random.NextBytes(iv);

			byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);

			IList headers = Platform.CreateArrayList(2);

			headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
			headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv)));

			return new PemObject(type, headers, encData);
		}
예제 #30
0
        public void doTestPadding(
			IBlockCipherPadding  padding,
			SecureRandom        rand,
			byte[]              ffVector,
			byte[]              ZeroVector)
        {
            PaddedBufferedBlockCipher    cipher = new PaddedBufferedBlockCipher(new DesEngine(), padding);
            KeyParameter                 key = new KeyParameter(Hex.Decode("0011223344556677"));

            //
            // ff test
            //
            byte[]    data = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0 };

            if (ffVector != null)
            {
                padding.AddPadding(data, 3);

                if (!AreEqual(data, ffVector))
                {
                    Fail("failed ff test for " + padding.PaddingName);
                }
            }

            //
            // zero test
            //
            if (ZeroVector != null)
            {
                data = new byte[8];
                padding.AddPadding(data, 4);

                if (!AreEqual(data, ZeroVector))
                {
                    Fail("failed zero test for " + padding.PaddingName);
                }
            }

            for (int i = 1; i != 200; i++)
            {
                data = new byte[i];

                rand.NextBytes(data);

                blockCheck(cipher, padding, key, data);
            }
        }
예제 #31
0
		public static KeyParameter MakeRandomKey(
            SymmetricKeyAlgorithmTag	algorithm,
            SecureRandom				random)
        {
            int keySize = GetKeySize(algorithm);
            byte[] keyBytes = new byte[(keySize + 7) / 8];
            random.NextBytes(keyBytes);
			return MakeKey(algorithm, keyBytes);
        }
예제 #32
0
        /// <summary>
        /// Encryption constructor to create a new random key from an intermediate
        /// </summary>
        public Bip38KeyPair(Bip38Intermediate intermediate, bool retainPrivateKeyWhenPossible=false)
        {
            // generate seedb
            byte[] seedb = new byte[24];
            SecureRandom sr = new SecureRandom();
            sr.NextBytes(seedb);

            // get factorb as sha256(sha256(seedb))
            Sha256Digest sha256 = new Sha256Digest();
            sha256.BlockUpdate(seedb, 0, 24);
            factorb = new byte[32];
            sha256.DoFinal(factorb, 0);
            sha256.BlockUpdate(factorb, 0, 32);
            sha256.DoFinal(factorb, 0);

            // get ECPoint from passpoint
            PublicKey pk = new PublicKey(intermediate.passpoint);

            ECPoint generatedpoint = pk.GetECPoint().Multiply(new BigInteger(1, factorb));
            byte[] generatedpointbytes = generatedpoint.GetEncoded();
            PublicKey generatedaddress = new PublicKey(generatedpointbytes);

            // get addresshash
            UTF8Encoding utf8 = new UTF8Encoding(false);
            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);

            byte[] addresshashplusownerentropy = new byte[12];
            Array.Copy(addresshashfull, 0, addresshashplusownerentropy, 0, 4);
            Array.Copy(intermediate.ownerentropy, 0, addresshashplusownerentropy, 4, 8);

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

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

            byte[] unencryptedpart1 = new byte[16];
            for (int i = 0; i < 16; i++) {
                unencryptedpart1[i] = (byte)(seedb[i] ^ derived[i]);
            }
            byte[] encryptedpart1 = new byte[16];

            // encrypt it
            var aes = Aes.Create();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform encryptor = aes.CreateEncryptor();

            encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0);
            encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0);

            byte[] unencryptedpart2 = new byte[16];
            for (int i = 0; i < 8; i++) {
                unencryptedpart2[i] = (byte)(encryptedpart1[i + 8] ^ derived[i + 16]);
            }
            for (int i = 0; i < 8; i++) {
                unencryptedpart2[i + 8] = (byte)(seedb[i + 16] ^ derived[i + 24]);
            }

            byte[] encryptedpart2 = new byte[16];
            encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0);
            encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0);

            byte[] result = new byte[39];
            result[0] = 0x01;
            result[1] = 0x43;
            result[2] = generatedaddress.IsCompressedPoint ? (byte)0x20 : (byte)0x00;
            if (intermediate.LotSequencePresent) result[2] |= 0x04;

            Array.Copy(addresshashfull, 0, result, 3, 4);
            Array.Copy(intermediate.ownerentropy, 0, result, 7, 8);
            Array.Copy(encryptedpart1, 0, result, 15, 8);
            Array.Copy(encryptedpart2, 0, result, 23, 16);

            _encryptedKey = Util.ByteArrayToBase58Check(result);
            _pubKey = generatedaddress.PublicKeyBytes;
            _hash160 = generatedaddress.Hash160;

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

            if (retainPrivateKeyWhenPossible && intermediate.passfactor != null) {
                BigInteger privatekey = new BigInteger(1, intermediate.passfactor).Multiply(new BigInteger(1, factorb)).Mod(ps.N);
                _privKey = new KeyPair(privatekey).PrivateKeyBytes;

            }

            // create the confirmation code
            confirmationCodeInfo = new byte[51];
            // constant provides for prefix "cfrm38"
            confirmationCodeInfo[0] = 0x64;
            confirmationCodeInfo[1] = 0x3B;
            confirmationCodeInfo[2] = 0xF6;
            confirmationCodeInfo[3] = 0xA8;
            confirmationCodeInfo[4] = 0x9A;
            // fields for flagbyte, addresshash, and ownerentropy all copy verbatim
            Array.Copy(result, 2, confirmationCodeInfo, 5, 1 + 4 + 8);
        }
예제 #33
0
		private void randomTest(
			SecureRandom	srng,
			IGcmMultiplier	m)
		{
			int kLength = 16 + 8 * srng.Next(3);
			byte[] K = new byte[kLength];
			srng.NextBytes(K);

			int pLength = srng.Next(1024);
			byte[] P = new byte[pLength];
			srng.NextBytes(P);

			int aLength = srng.Next(1024);
			byte[] A = new byte[aLength];
			srng.NextBytes(A);

			int ivLength = 1 + srng.Next(1024);
			byte[] IV = new byte[ivLength];
			srng.NextBytes(IV);

			GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine(), m);
			AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A);
			cipher.Init(true, parameters);
			byte[] C = new byte[cipher.GetOutputSize(P.Length)];
			int len = cipher.ProcessBytes(P, 0, P.Length, C, 0);
			len += cipher.DoFinal(C, len);

			if (C.Length != len)
			{
//				Console.WriteLine("" + C.Length + "/" + len);
				Fail("encryption reported incorrect length in randomised test");
			}

			byte[] encT = cipher.GetMac();
			byte[] tail = new byte[C.Length - P.Length];
			Array.Copy(C, P.Length, tail, 0, tail.Length);

			if (!AreEqual(encT, tail))
			{
				Fail("stream contained wrong mac in randomised test");
			}

			cipher.Init(false, parameters);
			byte[] decP = new byte[cipher.GetOutputSize(C.Length)];
			len = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
			len += cipher.DoFinal(decP, len);

			if (!AreEqual(P, decP))
			{
				Fail("incorrect decrypt in randomised test");
			}

			byte[] decT = cipher.GetMac();
			if (!AreEqual(encT, decT))
			{
				Fail("decryption produced different mac from encryption");
			}
		}
예제 #34
0
        /// <summary>
        /// Constructor that takes a single Escrow Invitation Code and produces a Payment Invitation Code.
        /// </summary>
        public EscrowCodeSet(string escrowInvitationCode, bool doCompressed=false, byte networkByte = 0)
        {
            byte[] pubpart, privpart;
            int identifier30;
            string failreason = parseEscrowCode(escrowInvitationCode, out pubpart, out privpart, out identifier30);
            if (failreason != null) throw new ArgumentException(failreason);

            // Look for mismatched parity.
            // (we expect LSB of einva's private part to be 0 and LSB of einvb's private part to be 1)
            // (this is to guarantee that einva's and einvb's private parts aren't equal)
            if ((escrowInvitationCode.StartsWith("einva") && (privpart[31] & 0x01) == 1) ||
                (escrowInvitationCode.StartsWith("einvb") && (privpart[31] & 0x01) == 0)) {
                throw new ArgumentException("This escrow invitation has mismatched parity.  Ask your escrow agent to " +
                    "generate a new pair using the latest version of the software.");
            }

            // Look for 48 0's or 48 1's
            if (privpart[0] == privpart[1] && privpart[1] == privpart[2] && privpart[2] == privpart[3] &&
               privpart[3] == privpart[4] && privpart[4] == privpart[5] && privpart[5] == privpart[6] &&
               privpart[6] == privpart[7] && privpart[7] == privpart[8]) {
                if (privpart[0] == 0x00 || privpart[0] == 0xFF) {
                    throw new ArgumentException("This escrow invitation is invalid and cannot be used (bad private key).");
                }
            }

            // produce a new factor
            byte[] z = new byte[32];
            SecureRandom sr = new SecureRandom();
            sr.NextBytes(z);

            // calculate Gxy then Gxyz
            PublicKey pk = new PublicKey(pubpart);
            ECPoint Gxyz = pk.GetECPoint().Multiply(new BigInteger(1, privpart)).Multiply(new BigInteger(1, z));

            // Uncompress it
            Gxyz = PublicKey.GetUncompressed(Gxyz);

            // We can get the Bitcoin address now, so do so
            PublicKey pkxyz = new PublicKey(Gxyz);
            byte[] hash160 = pkxyz.Hash160;
            BitcoinAddress = new AddressBase(hash160, networkByte).AddressBase58;

            // make the payment invitation record
            byte[] invp = new byte[74];
            long headP = headbaseP + (long)identifier30;
            for (int i = 7; i >= 0; i--) {
                invp[i] = (byte)(headP & 0xff);
                headP >>= 8;
            }
            invp[8] = networkByte;
            Array.Copy(z, 0, invp, 8 + 1 + 1, 32);

            // set flag to indicate if einvb was used to generate this, and make it available in the object
            if (escrowInvitationCode.StartsWith("einvb")) {
                invp[8 + 1 + 1 + 32 + 20] = 0x2;
            }

            // copy hash160
            Array.Copy(hash160, 0, invp, 8 + 1 + 1 + 32, 20);

            PaymentInvitationCode = Util.ByteArrayToBase58Check(invp);
            setAddressConfirmationCode(identifier30, networkByte, invp[8 + 1 + 1 + 32 + 20], z, hash160);
        }