public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
            {
                // get server password from database 
                string password = parentAssertion.Password;

                if (password == null)
                    return;

                // hash password
                password = SHA1(password);

                // create username token
                UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
                            PasswordOption.SendNone);

                if (parentAssertion.signRequest || parentAssertion.encryptRequest)
                {
                    // Add the token to the SOAP header.
                    security.Tokens.Add(userToken);
                }

                if (parentAssertion.signRequest)
                {
                    // Sign the SOAP message by using the UsernameToken.
                    MessageSignature sig = new MessageSignature(userToken);
                    security.Elements.Add(sig);
                }

                if (parentAssertion.encryptRequest)
                {
                    // we don't return any custom SOAP headers
                    // so, just encrypt a message Body
                    EncryptedData data = new EncryptedData(userToken);

                    // encrypt custom headers
                    for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
                    {
                        XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;

                        // find all SecureSoapHeader headers marked with a special attribute
                        if (child != null && child.NamespaceURI == "http://smbsaas/websitepanel/server/")
                        {
                            // create ID attribute for referencing purposes
                            string id = Guid.NewGuid().ToString();
                            child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);

                            // Create an encryption reference for the custom SOAP header.
                            data.AddReference(new EncryptionReference("#" + id));
                        }
                    }

                    security.Elements.Add(data);
                }
            }
예제 #2
11
            public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
            {
                // create username token
                UsernameToken userToken = new UsernameToken(parentAssertion.Username, parentAssertion.Password,
                            PasswordOption.SendNone);

                // Add the token to the SOAP header.
                security.Tokens.Add(userToken);

                // Sign the SOAP message by using the UsernameToken.
                MessageSignature sig = new MessageSignature(userToken);
                security.Elements.Add(sig);

                // Encrypt SOAP message
                EncryptedData data = new EncryptedData(userToken);
                security.Elements.Add(data);
            }
예제 #3
0
 public void Decrypt(string xmlFileName)
 {
     TripleDESCryptoServiceProvider encryptionKey = new TripleDESCryptoServiceProvider();
     encryptionKey.Key = UTF8Encoding.UTF8.GetBytes("");  // your salt value
     XmlDocument document = new XmlDocument();
     document.Load(xmlFileName);
     XmlElement encOrderElem = document.GetElementsByTagName("EncryptedData")[0] as XmlElement;
     EncryptedData encData = new EncryptedData();
     encData.LoadXml(encOrderElem);
     EncryptedXml encryptedXml = new EncryptedXml();
     byte[] decryptedOrder = encryptedXml.DecryptData(encData, encryptionKey);
     encryptedXml.ReplaceData(encOrderElem, decryptedOrder);
     document.Save(xmlFileName);
 }
	public byte[] DecryptData(EncryptedData encryptedData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) {}
예제 #5
0
        public string SayHello(string name)
        {
            SoapContext requestContext = Microsoft.Web.Services2.RequestSoapContext.Current;
            SoapContext responseContext = Microsoft.Web.Services2.ResponseSoapContext.Current;
            ISecurityTokenManager stm = SecurityTokenManager.GetSecurityTokenManagerByTokenType(WSTrust.TokenTypes.X509v3);
            X509SecurityTokenManager x509tm = stm as X509SecurityTokenManager;
            x509tm.DefaultSessionKeyAlgorithm = "TripleDES";

            //----------Encryption
            X509SecurityToken x509Token = getToken("client");
            if (x509Token == null) {
                //throw new SecurityFault(SecurityFault.FailedAuthenticationMessage, SecurityFault.FailedAuthenticationCode);
                throw new SecurityFault("Could not get encryption token...", SecurityFault.FailedAuthenticationCode);
            } else {
                EncryptedData ed = new EncryptedData(x509Token);
                responseContext.Security.Tokens.Add(x509Token);
                responseContext.Security.Elements.Add(ed);
            }

            //---------UsernameToken
            //			UsernameToken usernameToken = GetSigningToken() as UsernameToken;
            //			if (usernameToken == null || usernameToken.PasswordOption == PasswordOption.SendPlainText) {
            //				throw new SecurityFault(SecurityFault.FailedAuthenticationMessage, SecurityFault.FailedAuthenticationCode);
            //			}
            //
            //---------Signature
            //			//X509SecurityToken
            x509Token = getToken("server");
            X509SecurityToken x509TokenSigningToken = GetSigningToken() as X509SecurityToken;
            if (x509TokenSigningToken == null) { //|| !CompareArray(x509TokenSigningToken.KeyIdentifier.Value, Convert.FromBase64String(clientKeyIdentifier))) {
                throw new SecurityFault("Could not get signing token...", SecurityFault.FailedAuthenticationCode);
            } else {
                responseContext.Security.Tokens.Add(x509Token);
                responseContext.Security.Elements.Add(new MessageSignature(x509Token));
            }

            return "Hello," + name;
        }
예제 #6
0
        /// <summary>
        /// Decrypts the CipherText using the SecurityPolicyUri and returns the PlainTetx.
        /// </summary>
        public static byte[] Decrypt(X509Certificate2 certificate, string securityPolicyUri, EncryptedData dataToDecrypt)
        {
            // check if nothing to do.
            if (dataToDecrypt == null)
            {
                return null;
            }

            // nothing more to do if no encryption.
            if (String.IsNullOrEmpty(securityPolicyUri))
            {
                return dataToDecrypt.Data;
            }

            // decrypt data.
            switch (securityPolicyUri)
            {
                case SecurityPolicies.Basic256:
                {
                    if (dataToDecrypt.Algorithm == SecurityAlgorithms.RsaOaep)
                    {
                        return RsaUtils.Decrypt(new ArraySegment<byte>(dataToDecrypt.Data), certificate, true);
                    }
                        
                    break;
                }

                case SecurityPolicies.Basic128Rsa15:
                {
                    if (dataToDecrypt.Algorithm == SecurityAlgorithms.Rsa15)
                    {
                        return RsaUtils.Decrypt(new ArraySegment<byte>(dataToDecrypt.Data), certificate, false);
                    }
                    
                    break;
                }

                case SecurityPolicies.None:
                {
                    if (String.IsNullOrEmpty(dataToDecrypt.Algorithm))
                    {
                        return dataToDecrypt.Data;
                    }

                    break;
                }

                default:
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadSecurityPolicyRejected, 
                        "Unsupported security policy: {0}", 
                        securityPolicyUri);
                }
            }

            throw ServiceResultException.Create(
                StatusCodes.BadIdentityTokenInvalid, 
                "Unexpected encryption algorithm : {0}",
                dataToDecrypt.Algorithm);
        }
	public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri) {}
예제 #8
0
        /// <summary>
        /// An example on how to decrypt an encrypted assertion.
        /// </summary>
        private static void DecryptAssertion(string file)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(file);
            XmlElement encryptedDataElement = GetElement(dk.nita.saml20.Schema.XEnc.EncryptedData.ELEMENT_NAME, Saml20Constants.XENC, doc);


            EncryptedData encryptedData = new EncryptedData();

            encryptedData.LoadXml(encryptedDataElement);

            XmlNodeList nodelist = doc.GetElementsByTagName(dk.nita.saml20.Schema.XmlDSig.KeyInfo.ELEMENT_NAME, Saml20Constants.XMLDSIG);

            Assert.That(nodelist.Count > 0);

            KeyInfo key = new KeyInfo();

            key.LoadXml((XmlElement)nodelist[0]);

            // Review: Is it possible to figure out which certificate to load based on the Token?

            /*
             * Comment:
             * It would be possible to provide a key/certificate identifier in the EncryptedKey element, which contains the "recipient" attribute.
             * The implementation (Safewhere.Tokens.Saml20.Saml20EncryptedAssertion) currently just expects an appropriate asymmetric key to be provided,
             * and is not not concerned about its origin.
             * If the need arises, we can easily extend the Saml20EncryptedAssertion class with a property that allows extraction key info, eg. the "recipient"
             * attribute.
             */
            X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234");

            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm
            // Look through the list of KeyInfo elements to find the encrypted key.
            SymmetricAlgorithm symmetricKey = null;

            foreach (KeyInfoClause keyInfoClause in key)
            {
                if (keyInfoClause is KeyInfoEncryptedKey)
                {
                    KeyInfoEncryptedKey keyInfoEncryptedKey = (KeyInfoEncryptedKey)keyInfoClause;
                    EncryptedKey        encryptedKey        = keyInfoEncryptedKey.EncryptedKey;
                    symmetricKey = new RijndaelManaged();

                    symmetricKey.Key =
                        EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)cert.PrivateKey, false);
                    continue;
                }
            }
            // Explode if we didn't manage to find a viable key.
            Assert.IsNotNull(symmetricKey);
            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] plaintext = encryptedXml.DecryptData(encryptedData, symmetricKey);

            XmlDocument assertion = new XmlDocument();

            assertion.Load(new StringReader(System.Text.Encoding.UTF8.GetString(plaintext)));

            // A very simple test to ensure that there is indeed an assertion in the plaintext.
            Assert.AreEqual(Assertion.ELEMENT_NAME, assertion.DocumentElement.LocalName);
            Assert.AreEqual(Saml20Constants.ASSERTION, assertion.DocumentElement.NamespaceURI);
        }
예제 #9
0
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, RSA Alg, string KeyName)
        {
            // Check the arguments.
            if (Doc == null)
            {
                throw new ArgumentNullException("Doc");
            }
            if (ElementToEncrypt == null)
            {
                throw new ArgumentNullException("ElementToEncrypt");
            }
            if (Alg == null)
            {
                throw new ArgumentNullException("Alg");
            }

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////

            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");
            }

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // a new random symmetric key.
            //////////////////////////////////////////////////

            // Create a 256 bit Rijndael key.
            RijndaelManaged sessionKey = new RijndaelManaged();

            sessionKey.KeySize = 256;

            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);

            ////////////////////////////////////////////////
            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            ////////////////////////////////////////////////

            EncryptedData edElement = new EncryptedData();

            edElement.Type = EncryptedXml.XmlEncElementUrl;

            // Create an EncryptionMethod element so that the
            // receiver knows which algorithm to use for decryption.

            edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Encrypt the session key and add it to an EncryptedKey element.
            EncryptedKey ek = new EncryptedKey();

            byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false);

            ek.CipherData = new CipherData(encryptedKey);

            ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

            // Set the KeyInfo element to specify the
            // name of the RSA key.

            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();

            // Create a new KeyInfoName element.
            KeyInfoName kin = new KeyInfoName();

            // Specify a name for the key.
            kin.Value = KeyName;

            // Add the KeyInfoName element to the
            // EncryptedKey object.
            ek.KeyInfo.AddClause(kin);

            // Add the encrypted key to the
            // EncryptedData object.

            edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));

            // Add the encrypted element data to the
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////

            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }
        XmlElement VerifyInput2(MessageBuffer buf)
        {
            Message      msg2 = buf.CreateMessage();
            StringWriter sw   = new StringWriter();

            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw))) {
                msg2.WriteMessage(w);
            }
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(sw.ToString());

            // decrypt the key with service certificate privkey
            PaddingMode  mode   = PaddingMode.PKCS7;          // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
            EncryptedXml encXml = new EncryptedXml(doc);

            encXml.Padding = mode;
            X509Certificate2    cert2 = new X509Certificate2("Test/Resources/test.pfx", "mono");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
            nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#");
            nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
            XmlNode n = doc.SelectSingleNode("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);

            Assert.IsNotNull(n, "premise: enckey does not exist");
            string raw = n.InnerText;

            byte [] rawbytes             = Convert.FromBase64String(raw);
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey;

            byte [] decryptedKey = EncryptedXml.DecryptKey(rawbytes, rsa, true);             //rsa.Decrypt (rawbytes, true);

#if false
            // create derived keys
            Dictionary <string, byte[]>  keys = new Dictionary <string, byte[]> ();
            InMemorySymmetricSecurityKey skey =
                new InMemorySymmetricSecurityKey(decryptedKey);
            foreach (XmlElement el in doc.SelectNodes("//o:Security/c:DerivedKeyToken", nsmgr))
            {
                n = el.SelectSingleNode("c:Offset", nsmgr);
                int offset = (n == null) ? 0 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Length", nsmgr);
                int length = (n == null) ? 32 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Label", nsmgr);
                byte [] label = (n == null) ? decryptedKey :
                                Convert.FromBase64String(n.InnerText);
                n = el.SelectSingleNode("c:Nonce", nsmgr);
                byte [] nonce = (n == null) ? new byte [0] :
                                Convert.FromBase64String(n.InnerText);
                byte [] derkey = skey.GenerateDerivedKey(
                    //SecurityAlgorithms.Psha1KeyDerivation,
                    "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
                    label,
                    nonce,
                    length * 8,
                    offset);

                keys [el.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
            }
#endif

            // decrypt the signature with the decrypted key
#if true
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedSignature = ms.ToArray();
#else
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;

            EncryptedData ed = new EncryptedData();
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            ed.LoadXml(n as XmlElement);
            byte [] decryptedSignature = encXml.DecryptData(ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

            // decrypt the body with the decrypted key
#if true
            n = doc.SelectSingleNode("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            ms      = new MemoryStream();
            cs      = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedBody = ms.ToArray();
#else
            // decrypt the body with the decrypted key
            EncryptedData ed2 = new EncryptedData();
            XmlElement    el  = doc.SelectSingleNode("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
            ed2.LoadXml(el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            byte [] decryptedBody = encXml.DecryptData(ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
            Console.Error.WriteLine(Encoding.UTF8.GetString(decryptedBody));
            Console.Error.WriteLine("============= Decrypted Body End ===========");

            // FIXME: find out what first 16 bytes mean.
            for (int mmm = 0; mmm < 16; mmm++)
            {
                decryptedBody [mmm] = 0x20;
            }
            doc.LoadXml(Encoding.UTF8.GetString(decryptedBody));
            Assert.AreEqual("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
            Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

            return(doc.DocumentElement);
        }
예제 #11
0
        public void RoundtripSample1()
        {
            using (StringWriter sw = new StringWriter())
            {
                // Encryption
                {
                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml("<root>  <child>sample</child>   </root>");

                    XmlElement body = doc.DocumentElement;

                    using (Aes aes = Aes.Create())
                    {
                        aes.Mode    = CipherMode.CBC;
                        aes.KeySize = 256;
                        aes.IV      = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw==");
                        // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Unit test key.")]
                        aes.Key     = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640=");
                        aes.Padding = PaddingMode.Zeros;

                        EncryptedXml  exml      = new EncryptedXml();
                        byte[]        encrypted = exml.EncryptData(body, aes, false);
                        EncryptedData edata     = new EncryptedData();
                        edata.Type             = EncryptedXml.XmlEncElementUrl;
                        edata.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        EncryptedKey ekey = new EncryptedKey();
                        // omit key encryption, here for testing
                        byte[] encKeyBytes = aes.Key;
                        ekey.CipherData       = new CipherData(encKeyBytes);
                        ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
                        DataReference dr = new DataReference();
                        dr.Uri = "_0";
                        ekey.AddReference(dr);
                        edata.KeyInfo.AddClause(new KeyInfoEncryptedKey(ekey));
                        ekey.KeyInfo.AddClause(new RSAKeyValue(RSA.Create()));
                        edata.CipherData.CipherValue = encrypted;
                        EncryptedXml.ReplaceElement(doc.DocumentElement, edata, false);
                        doc.Save(new XmlTextWriter(sw));
                    }
                }

                // Decryption
                {
                    using (Aes aes = Aes.Create())
                    {
                        aes.Mode    = CipherMode.CBC;
                        aes.KeySize = 256;
                        // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Unit test key.")]
                        aes.Key     = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640=");
                        aes.Padding = PaddingMode.Zeros;

                        XmlDocument doc = new XmlDocument();
                        doc.PreserveWhitespace = true;
                        doc.LoadXml(sw.ToString());
                        EncryptedXml  encxml = new EncryptedXml(doc);
                        EncryptedData edata  = new EncryptedData();
                        edata.LoadXml(doc.DocumentElement);
                        encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes));
                    }
                }
            }
        }
예제 #12
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);
        }
예제 #13
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = ((Asn1OctetString)ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in certBags)
            {
                CertBag         certBag = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets  = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate cert    = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

                if (unmarkedKeyEntry != null)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Encrypt the element within the xml document.
        /// </summary>
        /// <param name="document">The xml document containing the element to encrypt.</param>
        /// <param name="elementToEncrypt">The element to encrypt in the xml document.</param>
        /// <param name="algorithm">The symmetric alogorithm used to encrypt the element.</param>
        /// <param name="keyName">The name to map to keyObject.</param>
        public void Encrypt(XmlDocument document, string elementToEncrypt, SymmetricAlgorithm algorithm, string keyName)
        {
            // Check the arguments.
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (string.IsNullOrEmpty(elementToEncrypt))
            {
                throw new ArgumentNullException("elementToEncrypt");
            }

            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentNullException("keyName");
            }

            if (document == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            XmlElement element = document.GetElementsByTagName(elementToEncrypt)[0] as XmlElement;

            // Throw an XmlException if the element was not found.
            if (element == null)
            {
                throw new XmlException("The specified element was not found");
            }

            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // symmetric key.
            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(element, algorithm, false);

            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            EncryptedData edElement = new EncryptedData();

            edElement.Type = EncryptedXml.XmlEncElementUrl;

            // Create an EncryptionMethod element so that the
            // receiver knows which algorithm to use for decryption.
            // Determine what kind of algorithm is being used and
            // supply the appropriate URL to the EncryptionMethod element.
            string encryptionMethod = null;

            if (algorithm is TripleDES)
            {
                encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
            }
            else if (algorithm is DES)
            {
                encryptionMethod = EncryptedXml.XmlEncDESUrl;
            }
            else if (algorithm is Rijndael)
            {
                switch (algorithm.KeySize)
                {
                case 128:
                    encryptionMethod = EncryptedXml.XmlEncAES128Url;
                    break;

                case 192:
                    encryptionMethod = EncryptedXml.XmlEncAES192Url;
                    break;

                case 256:
                    encryptionMethod = EncryptedXml.XmlEncAES256Url;
                    break;
                }
            }
            else
            {
                // Throw an exception if the transform is not in the previous categories
                throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
            }

            // Set the encryption method.
            edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);

            // Set the KeyInfo element to specify the
            // name of a key.
            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();

            // Create a new KeyInfoName element.
            KeyInfoName kin = new KeyInfoName();

            // Specify a name for the key.
            kin.Value = keyName;

            // Add the KeyInfoName element.
            edElement.KeyInfo.AddClause(kin);

            // Add the encrypted element data to the
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            EncryptedXml.ReplaceElement(element, edElement, false);
        }
예제 #15
0
        public void Load(
            Stream input,
            char[]  password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         unmarkedKey     = false;
            bool         wrongPkcs12Zero = false;

            if (bag.MacData != null)             // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.AreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.AreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();

            ArrayList chain = new ArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)ci.Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                if (b.BagAttributes != null)
                                {
                                    foreach (Asn1Sequence sq in b.BagAttributes)
                                    {
                                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                        Asn1Set             attrSet = (Asn1Set)sq[1];
                                        Asn1Encodable       attr    = null;

                                        if (attrSet.Count > 0)
                                        {
                                            // TODO We should be adding all attributes in the set
                                            attr = attrSet[0];

                                            // TODO We might want to "merge" attribute sets with
                                            // the same OID - currently, differing values give an error
                                            if (attributes.ContainsKey(aOid.Id))
                                            {
                                                // OK, but the value has to be the same
                                                if (!attributes[aOid.Id].Equals(attr))
                                                {
                                                    throw new IOException("attempt to add existing attribute with different value");
                                                }
                                            }
                                            else
                                            {
                                                attributes.Add(aOid.Id, attr);
                                            }

                                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                            {
                                                alias = ((DerBmpString)attr).GetString();
                                                // TODO Do these in a separate loop, just collect aliases here
                                                keys[alias] = pkcs12Key;
                                            }
                                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                            {
                                                localId = (Asn1OctetString)attr;
                                            }
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    byte[] hex  = Hex.Encode(localId.GetOctets());
                                    string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        // TODO There may have been more than one alias
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d      = EncryptedData.GetInstance(ci.Content);
                        byte[]        octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                            password, wrongPkcs12Zero, d.Content.GetOctets());
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.ContainsKey(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                byte[] hex  = Hex.Encode(localId.GetOctets());
                                string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo         privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                AsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.ContainsKey(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                byte[] hex  = Hex.Encode(localId.GetOctets());
                                string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("extra " + oid);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content));
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in chain)
            {
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                Hashtable       attributes = new Hashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                        Asn1Set             attrSet = (Asn1Set)sq[1];

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.ContainsKey(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        byte[] hex  = Hex.Encode(certId.Id);
                        string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                        keyCerts[name] = pkcs12Cert;

                        object temp = keys["unmarked"];
                        keys.Remove("unmarked");
                        keys[name] = temp;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        byte[] hex  = Hex.Encode(localId.GetOctets());
                        string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
예제 #16
0
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName)
        {
            if (Doc == null)
            {
                throw new ArgumentNullException("Doc");
            }
            if (ElementToEncrypt == null)
            {
                throw new ArgumentNullException("ElementToEncrypt");
            }
            if (EncryptionElementID == null)
            {
                throw new ArgumentNullException("EncryptionElementID");
            }
            if (Alg == null)
            {
                throw new ArgumentNullException("Alg");
            }
            if (KeyName == null)
            {
                throw new ArgumentNullException("KeyName");
            }


            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            RijndaelManaged sessionKey = null;

            try
            {
                //////////////////////////////////////////////////
                // Create a new instance of the EncryptedXml class
                // and use it to encrypt the XmlElement with the
                // a new random symmetric key.
                //////////////////////////////////////////////////

                // Create a 256 bit Rijndael key.
                sessionKey         = new RijndaelManaged();
                sessionKey.KeySize = 256;

                EncryptedXml eXml = new EncryptedXml();

                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
                ////////////////////////////////////////////////
                // Construct an EncryptedData object and populate
                // it with the desired encryption information.
                ////////////////////////////////////////////////

                EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
                edElement.Id   = EncryptionElementID;
                // Create an EncryptionMethod element so that the
                // receiver knows which algorithm to use for decryption.

                edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                // Encrypt the session key and add it to an EncryptedKey element.
                EncryptedKey ek = new EncryptedKey();

                byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false);

                ek.CipherData = new CipherData(encryptedKey);

                ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

                // Create a new DataReference element
                // for the KeyInfo element.  This optional
                // element specifies which EncryptedData
                // uses this key.  An XML document can have
                // multiple EncryptedData elements that use
                // different keys.
                DataReference dRef = new DataReference();

                // Specify the EncryptedData URI.
                dRef.Uri = "#" + EncryptionElementID;

                // Add the DataReference to the EncryptedKey.
                ek.AddReference(dRef);
                // Add the encrypted key to the
                // EncryptedData object.

                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
                // Set the KeyInfo element to specify the
                // name of the RSA key.


                // Create a new KeyInfoName element.
                KeyInfoName kin = new KeyInfoName();

                // Specify a name for the key.
                kin.Value = KeyName;

                // Add the KeyInfoName element to the
                // EncryptedKey object.
                ek.KeyInfo.AddClause(kin);
                // Add the encrypted element data to the
                // EncryptedData object.
                edElement.CipherData.CipherValue = encryptedElement;
                ////////////////////////////////////////////////////
                // Replace the element from the original XmlDocument
                // object with the EncryptedData element.
                ////////////////////////////////////////////////////
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            }
            catch (Exception e)
            {
                // re-throw the exception.
                // throw e;
            }
            finally
            {
                if (sessionKey != null)
                {
                    sessionKey.Clear();
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Encrypts the text using the SecurityPolicyUri and returns the result.
        /// </summary>
        public static EncryptedData Encrypt(X509Certificate2 certificate, string securityPolicyUri, byte[] plainText)
        {
            EncryptedData encryptedData = new EncryptedData();
        
            encryptedData.Algorithm = null;
            encryptedData.Data = plainText;

            // check if nothing to do.
            if (plainText == null)
            {
                return encryptedData;
            }

            // nothing more to do if no encryption.
            if (String.IsNullOrEmpty(securityPolicyUri))
            {
                return encryptedData;
            }

            // encrypt data.
            switch (securityPolicyUri)
            {
                case SecurityPolicies.Basic256:
                {
                    encryptedData.Algorithm = SecurityAlgorithms.RsaOaep;
                    encryptedData.Data = RsaUtils.Encrypt(plainText, certificate, true);
                    break;
                }
                    
                case SecurityPolicies.Basic128Rsa15:
                {
                    encryptedData.Algorithm = SecurityAlgorithms.Rsa15;
                    encryptedData.Data = RsaUtils.Encrypt(plainText, certificate, false);
                    break;
                }

                case SecurityPolicies.None:
                {
                    break;
                }

                default:
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadSecurityPolicyRejected, 
                        "Unsupported security policy: {0}", 
                        securityPolicyUri);
                }
            }
                   
            return encryptedData;
        }
예제 #18
0
        public HttpResponseMessage Post(ComUdtMemberGameInfoesInputParams p)
        {
            // try decrypt data
            if (!string.IsNullOrEmpty(p.token) && globalVal.CloudBreadCryptSetting == "AES256")
            {
                try
                {
                    string decrypted = Crypto.AES_decrypt(p.token, globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                    p = JsonConvert.DeserializeObject <ComUdtMemberGameInfoesInputParams>(decrypted);
                }
                catch (Exception ex)
                {
                    ex = (Exception)Activator.CreateInstance(ex.GetType(), "Decrypt Error", ex);
                    throw ex;
                }
            }

            // Get the sid or memberID of the current user.
            string sid = CBAuth.getMemberID(p.MemberID, this.User as ClaimsPrincipal);

            p.MemberID = sid;

            Logging.CBLoggers logMessage = new Logging.CBLoggers();
            string            jsonParam  = JsonConvert.SerializeObject(p);

            HttpResponseMessage response        = new HttpResponseMessage();
            EncryptedData       encryptedResult = new EncryptedData();
            RowcountResult      rowcountResult  = new RowcountResult();

            try
            {
                // task start log
                //logMessage.memberID = p.MemberID;
                //logMessage.Level = "INFO";
                //logMessage.Logger = "CBComUdtMemberGameInfoesController";
                //logMessage.Message = jsonParam;
                //Logging.RunLog(logMessage);

                /// Database connection retry policy
                RetryPolicy retryPolicy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>(globalVal.conRetryCount, TimeSpan.FromSeconds(globalVal.conRetryFromSeconds));
                using (SqlConnection connection = new SqlConnection(globalVal.DBConnectionString))
                {
                    using (SqlCommand command = new SqlCommand("uspComUdtMemberGameInfoes", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@MemberID", SqlDbType.NVarChar, -1).Value   = p.MemberID;
                        command.Parameters.Add("@Level", SqlDbType.NVarChar, -1).Value      = p.Level;
                        command.Parameters.Add("@Exps", SqlDbType.NVarChar, -1).Value       = p.Exps;
                        command.Parameters.Add("@Points", SqlDbType.NVarChar, -1).Value     = p.Points;
                        command.Parameters.Add("@UserSTAT1", SqlDbType.NVarChar, -1).Value  = p.UserSTAT1;
                        command.Parameters.Add("@UserSTAT2", SqlDbType.NVarChar, -1).Value  = p.UserSTAT2;
                        command.Parameters.Add("@UserSTAT3", SqlDbType.NVarChar, -1).Value  = p.UserSTAT3;
                        command.Parameters.Add("@UserSTAT4", SqlDbType.NVarChar, -1).Value  = p.UserSTAT4;
                        command.Parameters.Add("@UserSTAT5", SqlDbType.NVarChar, -1).Value  = p.UserSTAT5;
                        command.Parameters.Add("@UserSTAT6", SqlDbType.NVarChar, -1).Value  = p.UserSTAT6;
                        command.Parameters.Add("@UserSTAT7", SqlDbType.NVarChar, -1).Value  = p.UserSTAT7;
                        command.Parameters.Add("@UserSTAT8", SqlDbType.NVarChar, -1).Value  = p.UserSTAT8;
                        command.Parameters.Add("@UserSTAT9", SqlDbType.NVarChar, -1).Value  = p.UserSTAT9;
                        command.Parameters.Add("@UserSTAT10", SqlDbType.NVarChar, -1).Value = p.UserSTAT10;
                        command.Parameters.Add("@sCol1", SqlDbType.NVarChar, -1).Value      = p.sCol1;
                        command.Parameters.Add("@sCol2", SqlDbType.NVarChar, -1).Value      = p.sCol2;
                        command.Parameters.Add("@sCol3", SqlDbType.NVarChar, -1).Value      = p.sCol3;
                        command.Parameters.Add("@sCol4", SqlDbType.NVarChar, -1).Value      = p.sCol4;
                        command.Parameters.Add("@sCol5", SqlDbType.NVarChar, -1).Value      = p.sCol5;
                        command.Parameters.Add("@sCol6", SqlDbType.NVarChar, -1).Value      = p.sCol6;
                        command.Parameters.Add("@sCol7", SqlDbType.NVarChar, -1).Value      = p.sCol7;
                        command.Parameters.Add("@sCol8", SqlDbType.NVarChar, -1).Value      = p.sCol8;
                        command.Parameters.Add("@sCol9", SqlDbType.NVarChar, -1).Value      = p.sCol9;
                        command.Parameters.Add("@sCol10", SqlDbType.NVarChar, -1).Value     = p.sCol10;

                        connection.OpenWithRetry(retryPolicy);
                        using (SqlDataReader dreader = command.ExecuteReaderWithRetry(retryPolicy))
                        {
                            while (dreader.Read())
                            {
                                rowcountResult.result = dreader[0].ToString();
                            }
                            dreader.Close();
                        }
                        connection.Close();

                        // task end log
                        logMessage.memberID = p.MemberID;
                        logMessage.Level    = "INFO";
                        logMessage.Logger   = "CBComUdtMemberGameInfoesController";
                        logMessage.Message  = jsonParam;
                        Logging.RunLog(logMessage);

                        /// Encrypt the result response
                        if (globalVal.CloudBreadCryptSetting == "AES256")
                        {
                            try
                            {
                                encryptedResult.token = Crypto.AES_encrypt(JsonConvert.SerializeObject(rowcountResult), globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                                response = Request.CreateResponse(HttpStatusCode.OK, encryptedResult);
                                return(response);
                            }
                            catch (Exception ex)
                            {
                                ex = (Exception)Activator.CreateInstance(ex.GetType(), "Encrypt Error", ex);
                                throw ex;
                            }
                        }

                        response = Request.CreateResponse(HttpStatusCode.OK, rowcountResult);
                        return(response);
                    }
                }
            }

            catch (Exception ex)
            {
                // error log
                logMessage.memberID  = p.MemberID;
                logMessage.Level     = "ERROR";
                logMessage.Logger    = "CBComUdtMemberGameInfoesController";
                logMessage.Message   = jsonParam;
                logMessage.Exception = ex.ToString();
                Logging.RunLog(logMessage);

                throw;
            }
        }
		XmlElement VerifyInput2 (MessageBuffer buf)
		{
			Message msg2 = buf.CreateMessage ();
			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
				msg2.WriteMessage (w);
			}
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.LoadXml (sw.ToString ());

			// decrypt the key with service certificate privkey
			PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
			EncryptedXml encXml = new EncryptedXml (doc);
			encXml.Padding = mode;
			X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
			nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
			nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
			XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: enckey does not exist");
			string raw = n.InnerText;
			byte [] rawbytes = Convert.FromBase64String (raw);
			RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
			byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);

#if false
			// create derived keys
			Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
			InMemorySymmetricSecurityKey skey =
				new InMemorySymmetricSecurityKey (decryptedKey);
			foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
				n = el.SelectSingleNode ("c:Offset", nsmgr);
				int offset = (n == null) ? 0 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Length", nsmgr);
				int length = (n == null) ? 32 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Label", nsmgr);
				byte [] label = (n == null) ? decryptedKey :
					Convert.FromBase64String (n.InnerText);
				n = el.SelectSingleNode ("c:Nonce", nsmgr);
				byte [] nonce = (n == null) ? new byte [0] :
					Convert.FromBase64String (n.InnerText);
				byte [] derkey = skey.GenerateDerivedKey (
					//SecurityAlgorithms.Psha1KeyDerivation,
					"http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
					label,
					nonce,
					length * 8,
					offset);

				keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
			}
#endif

			// decrypt the signature with the decrypted key
#if true
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;
			MemoryStream ms = new MemoryStream ();
			CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedSignature = ms.ToArray ();
#else
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;

			EncryptedData ed = new EncryptedData ();
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			ed.LoadXml (n as XmlElement);
			byte [] decryptedSignature = encXml.DecryptData (ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

			// decrypt the body with the decrypted key
#if true
			n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			ms = new MemoryStream ();
			cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedBody = ms.ToArray ();
#else
			// decrypt the body with the decrypted key
			EncryptedData ed2 = new EncryptedData ();
			XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
			ed2.LoadXml (el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			byte [] decryptedBody = encXml.DecryptData (ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
Console.Error.WriteLine ("============= Decrypted Body End ===========");

			// FIXME: find out what first 16 bytes mean.
			for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
			doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
			Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

			return doc.DocumentElement;
		}
        /// <summary>
        /// Encryps the XML element.
        /// </summary>
        /// <param name="element"> The element to encrypt.</param>
        /// <param name="keyName"> The key name.</param>
        /// <returns> A EncryptedData type.</returns>
        public EncryptedData Encrypt(XmlElement element, string keyName)
        {
            // Get Key from key mappings
            RSA key = (RSA)_keyMappings[keyName];

            // Import key
            RSACryptoServiceProvider crypto = new RSACryptoServiceProvider();
            RSAParameters param = new RSAParameters();

            crypto.ImportParameters(key.ExportParameters(false));

            // Create session key
            RijndaelManaged sessionKey = new RijndaelManaged();
            sessionKey.KeySize = 256;

            // Encrypt the symmetric key and IV (session key encryption).
            byte[] encryptedSymmetricKey = crypto.Encrypt(sessionKey.Key, false);
            //byte[] encryptedSymmetricIV = crypto.Encrypt(sessionKey.IV, false);

            // Create a new EncryptedKey
            EncryptedKey ek = new EncryptedKey();
            ek.CipherData = new CipherData(encryptedSymmetricKey);
            ek.EncryptionMethod = new EncryptionMethod(EncryptXml.XmlEncRSA1_5Url);

            // set up a key info clause for the key that was used to encrypt the session key
            //			KeyInfoName keyName = new KeyInfoName();
            //			keyName.Value = keyName;
            // TODO: KeyInfo.AddClause.
            ek.KeyInfo = new KeyInfo(keyName);

            byte[] encryptedData = EncryptData(element, sessionKey);

            // create the encrypted data
            EncryptedData ed = new EncryptedData();
            ed.CipherData = new CipherData(encryptedData);
            //ed.Type = EncryptedXml.XmlEncElementUrl;
            ed.EncryptionMethod = new EncryptionMethod(EncryptXml.XmlEncAES256Url);
            ed.AddKeyInfoClause(new KeyInfoEncryptedKey(ek));

            return ed;
        }
	public virtual System.Security.Cryptography.SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) {}
 /// <summary>
 /// Replaces the current element.
 /// </summary>
 /// <param name="element"> The original element unencrypted.</param>
 /// <param name="encryptedElement"> The EncryptedData type.</param>
 public void ReplaceElement(XmlElement element, EncryptedData encryptedElement)
 {
     XmlNode encryptedNode = Serialize(encryptedElement);
     XmlNode newNode = _document.ImportNode(encryptedNode, true);
     element.ParentNode.ReplaceChild(newNode, element);
 }
	public static void ReplaceElement(System.Xml.XmlElement inputElement, EncryptedData encryptedData, bool content) {}
        private XmlNode Serialize(EncryptedData encryptedElement)
        {
            XmlSerializer ser = new XmlSerializer(typeof(EncryptedData));

            // Serialize object to xml
            StringWriter sw = new StringWriter( System.Globalization.CultureInfo.CurrentUICulture );
            ser.Serialize(sw, encryptedElement);
            sw.Flush();

            // Convert to a XmlNode
            XmlDocument doc = new XmlDocument();
            doc.LoadXml( sw.ToString() );

            return doc.DocumentElement;
        }
        private void ParseToken(string xmlToken, X509Certificate2 cert)
        {
            int skew = 300; // default to 5 minutes
            string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"];
            if (!string.IsNullOrEmpty(tokenskew))
                skew = Int32.Parse(tokenskew);

            XmlReader tokenReader = new XmlTextReader(new StringReader(xmlToken));
            EncryptedData enc = new EncryptedData();

            enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance;

            enc.ReadFrom(tokenReader);

            List<SecurityToken> tokens = new List<SecurityToken>();
            SecurityToken encryptingToken = new X509SecurityToken(cert);
            tokens.Add(encryptingToken);

            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
            SymmetricSecurityKey encryptingCrypto;

            // an error here usually means that you have selected the wrong key.
            encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]);

            SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod);

            byte[] decryptedData = enc.GetDecryptedBuffer(algorithm);

            SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));

            m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver);

            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                                            new SecurityTokenAuthenticator[]{
                                                                new RsaSecurityTokenAuthenticator(),
                                                                new X509SecurityTokenAuthenticator() }), new TimeSpan(0, 0, skew));

            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                m_identityClaims = FindIdentityClaims(m_authorizationContext);
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
예제 #26
0
            public override void SecureMessage(SoapEnvelope envelope, Security security)
            {
                UsernameToken userToken = new UsernameToken(
                    parentAssertion.username,
                    parentAssertion.password,
                    PasswordOption.SendNone); // we don't send password over network
                                              // but we just use username/password to sign/encrypt message

                // Add the token to the SOAP header.
                security.Tokens.Add(userToken);

                // Sign the SOAP message by using the UsernameToken.
                MessageSignature sig = new MessageSignature(userToken);
                security.Elements.Add(sig);

                // encrypt BODY
                EncryptedData data = new EncryptedData(userToken);

                // encrypt custom headers
                for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
                {
                    XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;

                    // find all SecureSoapHeader headers marked with a special attribute
                    if (child != null && child.NamespaceURI == "http://company.com/samples/wse/")
                    {
                        // create ID attribute for referencing purposes
                        string id = Guid.NewGuid().ToString();
                        child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);

                        // Create an encryption reference for the custom SOAP header.
                        data.AddReference(new EncryptionReference("#" + id));
                    }
                }

                // add ancrypted data to the security context
                security.Elements.Add(data);
            }
예제 #27
0
        private string ReadEncryptedData(TextReader stream, string password)
        {
            EncryptedData enc = new EncryptedData();
            stream.ReadLine(); // reads the header, we just ignore this
            enc.SaltString = stream.ReadLine();
            enc.MACString = stream.ReadLine();
            enc.DataString = stream.ReadToEnd();

            return DatabaseCrypto.Decrypt(password, enc);
        }
예제 #28
0
        /// <summary>
        /// Decrypts the Password using the EncryptionAlgorithm and places the result in DecryptedPassword
        /// </summary>
        public override void Decrypt(X509Certificate2 certificate, byte[] senderNonce, string securityPolicyUri)
        {
            // handle no encryption.
            if (String.IsNullOrEmpty(securityPolicyUri) || securityPolicyUri == SecurityPolicies.None)
            {
                DecryptedPassword = new UTF8Encoding().GetString(m_password);
                return;
            }
            
            // decrypt.
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.Data = m_password;
            encryptedData.Algorithm = m_encryptionAlgorithm;

            byte[] decryptedPassword = SecurityPolicies.Decrypt(
                certificate, 
                securityPolicyUri, 
                encryptedData);

            if (decryptedPassword == null)
            {
                m_decryptedPassword = null;
                return;
            }

            // verify the sender's nonce.
            int startOfNonce = decryptedPassword.Length;

            if (senderNonce != null)
            {
                 startOfNonce -= senderNonce.Length;

                for (int ii = 0; ii < senderNonce.Length; ii++)
                {
                    if (senderNonce[ii] != decryptedPassword[ii+startOfNonce])
                    {
                        throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                    }
                }
            }            
                     
            // convert to UTF-8.
            DecryptedPassword = new UTF8Encoding().GetString(decryptedPassword, 0, startOfNonce);
        }
예제 #29
0
 public void Encrypt(string xmlFileName)
 {
     TripleDESCryptoServiceProvider encryptionKey = new TripleDESCryptoServiceProvider();
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlFileName);
     encryptionKey.Key = UTF8Encoding.UTF8.GetBytes("");  // your salt value
     XmlElement orderElem = xmlDoc.SelectSingleNode("Settings") as XmlElement;
     EncryptedXml encXml = new EncryptedXml(xmlDoc);
     byte[] encryptedOrder = encXml.EncryptData(orderElem, encryptionKey, false);
     EncryptedData encryptedData = new EncryptedData();
     encryptedData.Type = EncryptedXml.XmlEncElementUrl;
     encryptedData.EncryptionMethod = new
     EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);
     encryptedData.CipherData = new CipherData();
     encryptedData.CipherData.CipherValue = encryptedOrder;
     EncryptedXml.ReplaceElement(orderElem, encryptedData, false);
     xmlDoc.Save(xmlFileName);
 }
예제 #30
0
        /// <summary>
        /// Decrypts the Password using the EncryptionAlgorithm and places the result in DecryptedPassword
        /// </summary>
        public override void Decrypt(X509Certificate2 certificate, byte[] senderNonce, string securityPolicyUri)
        {
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.Data = m_tokenData;
            encryptedData.Algorithm = m_encryptionAlgorithm;

            byte[] decryptedTokenData = SecurityPolicies.Decrypt(
                certificate, 
                securityPolicyUri, 
                encryptedData);

            // verify the sender's nonce.
            int startOfNonce = decryptedTokenData.Length;

            if (senderNonce != null)
            {
                startOfNonce -= senderNonce.Length;

                for (int ii = 0; ii < senderNonce.Length; ii++)
                {
                    if (senderNonce[ii] != decryptedTokenData[ii+startOfNonce])
                    {
                        throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                    }
                }
            }         
   
            // copy results.
            m_decryptedTokenData = new byte[startOfNonce];
            Array.Copy(decryptedTokenData, m_decryptedTokenData, startOfNonce);                     
        }
예제 #31
0
		EncryptedData Encrypt (XmlElement target, SymmetricAlgorithm actualKey, string ekeyId, ReferenceList refList, SecurityKeyIdentifierClause encClause, EncryptedXml exml, XmlDocument doc)
		{
			SecurityAlgorithmSuite suite = security.Element.DefaultAlgorithmSuite;
			SecurityTokenSerializer serializer = security.TokenSerializer;

			byte [] encrypted = exml.EncryptData (target, actualKey, false);
			EncryptedData edata = new EncryptedData ();
			edata.Id = GenerateId (doc);
			edata.Type = EncryptedXml.XmlEncElementContentUrl;
			edata.EncryptionMethod = new EncryptionMethod (suite.DefaultEncryptionAlgorithm);
			// FIXME: here wsse:DigestMethod should be embedded 
			// inside EncryptionMethod. Since it is not possible 
			// with S.S.C.Xml.EncryptionMethod, we will have to
			// build our own XML encryption classes.

			edata.CipherData.CipherValue = encrypted;

			DataReference dr = new DataReference ();
			dr.Uri = "#" + edata.Id;
			refList.Add (dr);

			if (ShouldOutputEncryptedKey && !CounterParameters.RequireDerivedKeys)
				edata.KeyInfo = null;
			else {
				edata.KeyInfo = new KeyInfo ();
				edata.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (encClause, serializer, doc));
			}

			return edata;
		}
예제 #32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="ElementName">Ruta completa del elemento a encriptar
        /// Ejemplos:
        /// <example>
        /// Encripta el precio los libros cuyo precio es mayor a 35
        /// /bookstore/book[price>35]/price
        ///
        /// Busca el grupos "ValidationExceptionMessage" y dentro de este la clave con nombre "MaxLenghtField"
        ///         "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
        ///
        ///
        /// "//EXAMPLE/CUSTOMER[substring(@type,1,2) ='DE']"
        /// "//EXAMPLE/CUSTOMER[contains(@type,'DECEA')]"
        /// </example>
        /// </param>
        /// <param name="Key"></param>
        public static string Encrypt(string xml, string elementPath, SymmetricAlgorithm symmetricAlgorithm)
        {
            // Check the arguments.
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentNullException("xml");
            }
            if (string.IsNullOrEmpty(elementPath))
            {
                throw new ArgumentNullException("elementPath");
            }
            if (symmetricAlgorithm == null)
            {
                throw new ArgumentNullException("SymmetricAlgorithm");
            }


            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xml);

            ///bookstore/book[price>35]/price
            /// "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
            XmlElement elementToEncrypt = xmlDoc.SelectSingleNode(elementPath) as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");
            }


            //////////////////////////////////////////////////
            // Creo una instancia de EncryptedXml y la uso
            // para encriptar XmlElement con lka clave simetrica
            //////////////////////////////////////////////////
            EncryptedXml eXml = new EncryptedXml();


            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false);

            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            EncryptedData edElement = new EncryptedData();

            edElement.Type             = EncryptedXml.XmlEncElementUrl;
            edElement.EncryptionMethod = GetEncrypTionMethod(symmetricAlgorithm);

            //// Add the encrypted element data to the EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();


            //// Encrypt the session key and add it to an EncryptedKey element.
            //EncryptedKey ek = new EncryptedKey();


            //// Create a new KeyInfoName element.
            //KeyInfoName kin = new KeyInfoName();

            //// Specify a name for the key.
            //kin.Value = KeyName;

            //// Add the KeyInfoName element to the
            //// EncryptedKey object.
            //ek.KeyInfo.AddClause(kin);

            // Add the encrypted key to the
            // EncryptedData object.

            //edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));



            // Replace the element from the original XmlDocument   object with the EncryptedData element.
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            symmetricAlgorithm.Clear();
            xml    = xmlDoc.InnerXml;
            xmlDoc = null;
            return(xml);
        }