示例#1
0
        internal static IWrapper CreateWrapper(SymmetricKeyAlgorithmTag encAlgorithm)
        {
            switch (encAlgorithm)
            {
            case SymmetricKeyAlgorithmTag.Aes128:
            case SymmetricKeyAlgorithmTag.Aes192:
            case SymmetricKeyAlgorithmTag.Aes256:
                return(WrapperUtilities.GetWrapper("AESWRAP"));

            case SymmetricKeyAlgorithmTag.Camellia128:
            case SymmetricKeyAlgorithmTag.Camellia192:
            case SymmetricKeyAlgorithmTag.Camellia256:
                return(WrapperUtilities.GetWrapper("CAMELLIAWRAP"));

            default:
                throw new PgpException("unknown wrap algorithm: " + encAlgorithm);
            }
        }
        internal KeyParameter UnwrapKey(ICipherParameters key)
        {
            byte[] encryptedKey = info.EncryptedKey.GetOctets();


            try
            {
                if (keyEncAlg.Algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
                {
                    IKeyUnwrapper keyWrapper = new Asn1KeyUnwrapper(keyEncAlg.Algorithm, keyEncAlg.Parameters, key);

                    return(ParameterUtilities.CreateKeyParameter(
                               GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length).Collect()));
                }
                else
                {
                    string   keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(keyEncAlg);
                    IWrapper keyWrapper           = WrapperUtilities.GetWrapper(keyExchangeAlgorithm);
                    keyWrapper.Init(false, key);

                    // FIXME Support for MAC algorithm parameters similar to cipher parameters
                    return(ParameterUtilities.CreateKeyParameter(
                               GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length)));
                }
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
//			catch (IllegalBlockSizeException e)
            catch (DataLengthException e)
            {
                throw new CmsException("illegal blocksize in message.", e);
            }
//			catch (BadPaddingException e)
            catch (InvalidCipherTextException e)
            {
                throw new CmsException("bad padding in message.", e);
            }
        }
 public override CmsTypedStream GetContentStream(ICipherParameters key)
 {
     try
     {
         byte[]   octets  = info.EncryptedKey.GetOctets();
         IWrapper wrapper = WrapperUtilities.GetWrapper(keyEncAlg.Algorithm.Id);
         wrapper.Init(forWrapping: false, key);
         KeyParameter sKey = ParameterUtilities.CreateKeyParameter(GetContentAlgorithmName(), wrapper.Unwrap(octets, 0, octets.Length));
         return(GetContentFromSessionKey(sKey));
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("couldn't create cipher.", e);
     }
     catch (InvalidKeyException e2)
     {
         throw new CmsException("key invalid in message.", e2);
     }
 }
示例#4
0
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
            ICipherParameters key)
        {
            try
            {
                AlgorithmIdentifier kekAlg       = AlgorithmIdentifier.GetInstance(info.KeyEncryptionAlgorithm);
                Asn1Sequence        kekAlgParams = (Asn1Sequence)kekAlg.Parameters;
                byte[]   encryptedKey            = info.EncryptedKey.GetOctets();
                string   kekAlgName = DerObjectIdentifier.GetInstance(kekAlgParams[0]).Id;
                string   cName      = CmsEnvelopedHelper.Instance.GetRfc3211WrapperName(kekAlgName);
                IWrapper keyWrapper = WrapperUtilities.GetWrapper(cName);

                byte[] iv = Asn1OctetString.GetInstance(kekAlgParams[1]).GetOctets();

                ICipherParameters parameters = ((CmsPbeKey)key).GetEncoded(kekAlgName);
                parameters = new ParametersWithIV(parameters, iv);

                keyWrapper.Init(false, parameters);

                AlgorithmIdentifier aid = GetActiveAlgID();

                string alg = aid.ObjectID.Id;

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
                    alg, keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
        }
示例#5
0
        /**
         * decrypt the content and return an input stream.
         */
        public override async Task <CmsTypedStream> GetContentStream(
            ICipherParameters key)
        {
            try
            {
                byte[]   encryptedKey = info.EncryptedKey.GetOctets();
                IWrapper keyWrapper   = WrapperUtilities.GetWrapper(keyEncAlg.ObjectID.Id);

                keyWrapper.Init(false, key);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
                    GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));

                return(await GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
        }
        /**
         * decrypt the content and return it as a byte array.
         */
        public override CmsTypedStream GetContentStream(
            ICipherParameters key)
        {
            byte[] encryptedKey         = _info.EncryptedKey.GetOctets();
            string keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(_keyEncAlg.ObjectID);

            try
            {
                IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyExchangeAlgorithm);

                keyWrapper.Init(false, key);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
                    _encAlg.ObjectID, keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
//			catch (IllegalBlockSizeException e)
            catch (DataLengthException e)
            {
                throw new CmsException("illegal blocksize in message.", e);
            }
//			catch (BadPaddingException e)
            catch (InvalidCipherTextException e)
            {
                throw new CmsException("bad padding in message.", e);
            }
        }
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
//			Key key)
            ICipherParameters key)
        {
            if (!(key is AsymmetricKeyParameter))
            {
                throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
            }

            AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key;

            if (!privKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "key");
            }

            try
            {
                OriginatorPublicKey    origK    = _info.Originator.OriginatorKey;
                PrivateKeyInfo         privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
                SubjectPublicKeyInfo   pubInfo  = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes());
                AsymmetricKeyParameter pubKey   = PublicKeyFactory.CreateKey(pubInfo);

                string wrapAlg = DerObjectIdentifier.GetInstance(
                    Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id;

                IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    _keyEncAlg.ObjectID, wrapAlg);

                agreement.Init(privKey);

                BigInteger wKeyNum = agreement.CalculateAgreement(pubKey);
                // TODO Fix the way bytes are derived from the secret
                byte[]       wKeyBytes = wKeyNum.ToByteArrayUnsigned();
                KeyParameter wKey      = ParameterUtilities.CreateKeyParameter(wrapAlg, wKeyBytes);

                IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);

                keyCipher.Init(false, wKey);

                AlgorithmIdentifier aid = _encAlg;
                string alg = aid.ObjectID.Id;

                byte[] encryptedKey = _encryptedKey.GetOctets();
                byte[] sKeyBytes    = keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(alg, sKeyBytes);

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (Exception e)
            {
                throw new CmsException("originator key invalid.", e);
            }
        }
示例#8
0
        private const string alg = "1.2.840.113549.1.12.1.3";         // 3 key triple DES with SHA-1

        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");

            fact.Init(new KeyGenerationParameters(new SecureRandom(), 512));

            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter priKey = keyPair.Private;
            AsymmetricKeyParameter pubKey = keyPair.Public;

            //
            // set up the parameters
            //
            byte[]        salt           = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int           iterationCount = 100;
            Asn1Encodable defParams      = PbeUtilities.GenerateAlgorithmParameters(alg, salt, iterationCount);

            char[] password1 = { 'h', 'e', 'l', 'l', 'o' };

//				AlgorithmParameters parameters = AlgorithmParameters.getInstance(alg);
//
//				parameters.init(defParams);

            //
            // set up the key
            //
//				PBEKeySpec pbeSpec = new PBEKeySpec(password1);
//				SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg);

//				IBufferedCipher cipher = CipherUtilities.GetCipher(alg);
            IWrapper wrapper = WrapperUtilities.GetWrapper(alg);

            ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(
                alg, password1, defParams);

//				cipher.Init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//				byte[] wrappedKey = cipher.Wrap(priKey);
            byte[] pkb        = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();
            byte[] wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//				EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(parameters, wrappedKey);
            PrivateKeyInfo          plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            EncryptedPrivateKeyInfo pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);


            //
            // decryption step
            //
            char[] password2 = { 'h', 'e', 'l', 'l', 'o' };

//				pbeSpec = new PBEKeySpec(password2);
//
//				cipher = CipherUtilities.GetCipher(pInfo.EncryptionAlgorithm);
//
//				cipher.Init(false, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//				PKCS8EncodedKeySpec keySpec = pInfo.getKeySpec(cipher);
            PrivateKeyInfo decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//				if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }

            //
            // using ICipherParameters test
            //
//			pbeSpec = new PBEKeySpec(password1);
//			keyFact = SecretKeyFactory.getInstance(alg);
//			cipher = CipherUtilities.GetCipher(alg);
            wrapper = WrapperUtilities.GetWrapper(alg);

//			cipher.init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//			wrappedKey = cipher.wrap(priKey);
            wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//			pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);
            plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);

            //
            // decryption step
            //
//			pbeSpec = new PBEKeySpec(password2);
//
//			cipher = CipherUtilities.GetCipher(pInfo.getAlgName());
//
//			cipher.init(IBufferedCipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//			keySpec = pInfo.getKeySpec(cipher);
            decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//			if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }
        }