GetKey() public method

public GetKey ( ) : byte[]
return byte[]
		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 void checkKeyParameter(
			KeyParameter	key,
			Type			expectedType,
			byte[]			expectedBytes)
		{
			Assert.IsTrue(expectedType.IsInstanceOfType(key));
			Assert.IsTrue(Arrays.AreEqual(expectedBytes, key.GetKey()));
		}
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
			keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
        	Asn1OctetString encryptedKey = new DerOctetString(
				keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

			return new RecipientInfo(new KekRecipientInfo(kekIdentifier, keyEncryptionAlgorithm, encryptedKey));
		}
Beispiel #4
0
        /**
         * Generate a new instance of an TlsMac.
         *
         * @param context the TLS client context
         * @param digest  The digest to use.
         * @param key     A byte-array where the key for this MAC is located.
         * @param keyOff  The number of bytes to skip, before the key starts in the buffer.
         * @param keyLen  The length of the key.
         */
        public TlsMac(TlsContext context, IDigest digest, byte[] key, int keyOff, int keyLen)
        {
            this.context = context;

            KeyParameter keyParameter = new KeyParameter(key, keyOff, keyLen);

            this.secret = Arrays.Clone(keyParameter.GetKey());

            // TODO This should check the actual algorithm, not rely on the engine type
            if (digest is LongDigest)
            {
                this.digestBlockSize = 128;
                this.digestOverhead = 16;
            }
            else
            {
                this.digestBlockSize = 64;
                this.digestOverhead = 8;
            }

            if (TlsUtilities.IsSsl(context))
            {
                this.mac = new Ssl3Mac(digest);

                // TODO This should check the actual algorithm, not assume based on the digest size
                if (digest.GetDigestSize() == 20)
                {
                    /*
                     * NOTE: When SHA-1 is used with the SSL 3.0 MAC, the secret + input pad is not
                     * digest block-aligned.
                     */
                    this.digestOverhead = 4;
                }
            }
            else
            {
                this.mac = new HMac(digest);

                // NOTE: The input pad for HMAC is always a full digest block
            }

            this.mac.Init(keyParameter);

            this.macLength = mac.GetMacSize();
            if (context.SecurityParameters.truncatedHMac)
            {
                this.macLength = System.Math.Min(this.macLength, 10);
            }
        }
Beispiel #5
0
        /**
        * Generate a new instance of an TlsMac.
        *
        * @param digest    The digest to use.
        * @param key_block A byte-array where the key for this mac is located.
        * @param offset    The number of bytes to skip, before the key starts in the buffer.
        * @param len       The length of the key.
        */
        public TlsMac(
            IDigest	digest,
            byte[]	key_block,
            int		offset,
            int		len)
        {
            this.seqNo = 0;

            KeyParameter param = new KeyParameter(key_block, offset, len);

            this.secret = Arrays.Clone(param.GetKey());

            this.mac = new HMac(digest);
            this.mac.Init(param);
        }
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();
			AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID;

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
			keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random));
			byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

			RecipientIdentifier recipId;
			if (recipientTbsCert != null)
			{
				IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(
					recipientTbsCert.Issuer, recipientTbsCert.SerialNumber.Value);
				recipId = new RecipientIdentifier(issuerAndSerial);
			}
			else
			{
				recipId = new RecipientIdentifier(subjectKeyIdentifier);
			}

			return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncryptionAlgorithm,
				new DerOctetString(encryptedKeyBytes)));
		}
		private static AlgorithmIdentifier DetermineKeyEncAlg(
			string algorithm, KeyParameter key)
		{
			if (algorithm.StartsWith("DES"))
			{
				return new AlgorithmIdentifier(
					PkcsObjectIdentifiers.IdAlgCms3DesWrap,
					DerNull.Instance);
			}
			else if (algorithm.StartsWith("RC2"))
			{
				return new AlgorithmIdentifier(
					PkcsObjectIdentifiers.IdAlgCmsRC2Wrap,
					new DerInteger(58));
			}
			else if (algorithm.StartsWith("AES"))
			{
				int length = key.GetKey().Length * 8;
				DerObjectIdentifier wrapOid;

				if (length == 128)
				{
					wrapOid = NistObjectIdentifiers.IdAes128Wrap;
				}
				else if (length == 192)
				{
					wrapOid = NistObjectIdentifiers.IdAes192Wrap;
				}
				else if (length == 256)
				{
					wrapOid = NistObjectIdentifiers.IdAes256Wrap;
				}
				else
				{
					throw new ArgumentException("illegal keysize in AES");
				}

				return new AlgorithmIdentifier(wrapOid);  // parameters absent
			}
			else if (algorithm.StartsWith("SEED"))
			{
				// parameters absent
				return new AlgorithmIdentifier(KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap);
			}
			else if (algorithm.StartsWith("CAMELLIA"))
			{
				int length = key.GetKey().Length * 8;
				DerObjectIdentifier wrapOid;

				if (length == 128)
				{
					wrapOid = NttObjectIdentifiers.IdCamellia128Wrap;
				}
				else if (length == 192)
				{
					wrapOid = NttObjectIdentifiers.IdCamellia192Wrap;
				}
				else if (length == 256)
				{
					wrapOid = NttObjectIdentifiers.IdCamellia256Wrap;
				}
				else
				{
					throw new ArgumentException("illegal keysize in Camellia");
				}

				return new AlgorithmIdentifier(wrapOid); // parameters must be absent
			}
			else
			{
				throw new ArgumentException("unknown algorithm");
			}
		}
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            IAsymmetricKeyParameter senderPublicKey = senderKeyPair.Public;
            ICipherParameters senderPrivateParams = senderKeyPair.Private;

            OriginatorIdentifierOrKey originator;
            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }

            Asn1OctetString ukm = null;
            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    IAsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }

            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);

            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();
            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                IBigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                new DerSequence(recipientEncryptedKeys)));
        }
		private byte[] CreateSessionInfo(
			SymmetricKeyAlgorithmTag	algorithm,
			KeyParameter				key)
		{
			byte[] keyBytes = key.GetKey();
			byte[] sessionInfo = new byte[keyBytes.Length + 3];
			sessionInfo[0] = (byte) algorithm;
			keyBytes.CopyTo(sessionInfo, 1);
			AddCheckSum(sessionInfo);
			return sessionInfo;
		}
			internal RecipientInfo ToRecipientInfo(
				KeyParameter	key,
				SecureRandom	random)
			{
				byte[] keyBytes = key.GetKey();

				if (pubKey != null)
				{
					IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

					keyWrapper.Init(true, new ParametersWithRandom(pubKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					RecipientIdentifier recipId;
					if (cert != null)
					{
						TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
							Asn1Object.FromByteArray(cert.GetTbsCertificate()));

						Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
							tbs.Issuer, tbs.SerialNumber.Value);

						recipId = new RecipientIdentifier(encSid);
					}
					else
					{
						recipId = new RecipientIdentifier(subKeyId);
					}

					return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey));
				}
				else if (originator != null)
				{
					IWrapper keyWrapper = Helper.CreateWrapper(
						DerObjectIdentifier.GetInstance(
							Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id);

					keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					RecipientEncryptedKey rKey = new RecipientEncryptedKey(
						new KeyAgreeRecipientIdentifier(
							new Asn1.Cms.IssuerAndSerialNumber(
								PrincipalUtilities.GetIssuerX509Principal(cert),
								cert.SerialNumber)),
						encKey);

					return new RecipientInfo(
						new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey)));
				}
				else if (derivationAlg != null)
				{
					string rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm);
					IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);


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


					ICipherParameters parameters = new ParametersWithIV(secKey, iv);
					keyWrapper.Init(true, new ParametersWithRandom(parameters, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

//					byte[] iv = keyWrapper.GetIV();

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

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

					return new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey));
				}
				else
				{
					IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

					keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					return new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey));
				}
			}
			internal RecipientInf(
				string			secKeyAlgorithm, // TODO Can get this from secKey?
				KeyParameter	secKey,
				KekIdentifier	secKeyId)
			{
				this.secKeyAlgorithm = secKeyAlgorithm;
				this.secKey = secKey;
				this.secKeyId = secKeyId;

				if (secKeyAlgorithm.StartsWith("DES"))
				{
					keyEncAlg = new AlgorithmIdentifier(
						PkcsObjectIdentifiers.IdAlgCms3DesWrap,
						DerNull.Instance);
				}
				else if (secKeyAlgorithm.StartsWith("RC2"))
				{
					keyEncAlg = new AlgorithmIdentifier(
						PkcsObjectIdentifiers.IdAlgCmsRC2Wrap,
						new DerInteger(58));
				}
				else if (secKeyAlgorithm.StartsWith("AES"))
				{
					int length = secKey.GetKey().Length * 8;
					DerObjectIdentifier wrapOid;

					if (length == 128)
					{
						wrapOid = NistObjectIdentifiers.IdAes128Wrap;
					}
					else if (length == 192)
					{
						wrapOid = NistObjectIdentifiers.IdAes192Wrap;
					}
					else if (length == 256)
					{
						wrapOid = NistObjectIdentifiers.IdAes256Wrap;
					}
					else
					{
						throw new ArgumentException("illegal keysize in AES");
					}

					keyEncAlg = new AlgorithmIdentifier(wrapOid);  // parameters absent
				}
				else if (secKeyAlgorithm.StartsWith("SEED"))
				{
					// parameters absent
					keyEncAlg = new AlgorithmIdentifier(KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap);
				}
				else if (secKeyAlgorithm.StartsWith("CAMELLIA"))
				{
					int length = secKey.GetKey().Length * 8;
					DerObjectIdentifier wrapOid;

					if (length == 128)
					{
						wrapOid = NttObjectIdentifiers.IdCamellia128Wrap;
					}
					else if (length == 192)
					{
						wrapOid = NttObjectIdentifiers.IdCamellia192Wrap;
					}
					else if (length == 256)
					{
						wrapOid = NttObjectIdentifiers.IdCamellia256Wrap;
					}
					else
					{
						throw new ArgumentException("illegal keysize in Camellia");
					}

					keyEncAlg = new AlgorithmIdentifier(wrapOid); // parameters must be absent
				}
				else
				{
					throw new ArgumentException("unknown algorithm");
				}
			}
        protected virtual KeyParameter InitRecordMac(ChaChaEngine cipher, bool forEncryption, long seqNo)
        {
            byte[] nonce = new byte[8];
            TlsUtilities.WriteUint64(seqNo, nonce, 0);

            cipher.Init(forEncryption, new ParametersWithIV(null, nonce));

            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            // NOTE: The BC implementation puts 'r' after 'k'
            Array.Copy(firstBlock, 0, firstBlock, 32, 16);
            KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);
            Poly1305KeyGenerator.Clamp(macKey.GetKey());
            return macKey;
        }