Exemplo n.º 1
0
        public static string EncryptPKCS8(string data, string publicKey)
        {
            Asn1Object   obj = Asn1Object.FromByteArray(Convert.FromBase64String(publicKey));
            DerSequence  publicKeySequence = (DerSequence)obj;
            DerBitString encodedPublicKey  = (DerBitString)publicKeySequence[1];

            DerSequence publicKeyDer = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());
            DerInteger  modulus      = (DerInteger)publicKeyDer[0];
            DerInteger  exponent     = (DerInteger)publicKeyDer[1];

            RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
            //Then, BouncyCastle provides an easy way to convert this to.NET compatible RSAParameters:
            RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
            //You can then easily import the key parameters into RSACryptoServiceProvider:
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(parameters);
            //Finally, do your encryption:
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(data);
            // Sign data with Pkcs1
            byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
            // Convert Bytes to Hash
            var hash = Convert.ToBase64String(encryptedData);

            return(hash);
        }
Exemplo n.º 2
0
		private AsymmetricECPrivateKey(Algorithm ecAlg, AlgorithmIdentifier algorithmIdentifier, ECPrivateKeyStructure privateKey): base(ecAlg, algorithmIdentifier)
		{
			this.d = privateKey.GetKey();
			DerBitString wEnc = privateKey.GetPublicKey();
			// really this should be getOctets() but there are keys with padbits out in the wild
			this.publicKey = (wEnc == null) ? null : wEnc.GetBytes();
			this.hashCode = calculateHashCode();
		}
Exemplo n.º 3
0
        /// <summary>
        /// The encode public key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string EncodePublicKey(PublicKey key)
        {
            SubjectPublicKeyInfo publicKeyInfo = key.GetPublicKeyInfo();
            DerBitString         bitString     = publicKeyInfo.PublicKeyData;

            byte[] data    = bitString.GetBytes();
            string encoded = Convert.ToBase64String(data);

            return(encoded);
        }
Exemplo n.º 4
0
        private void DoTestZeroLengthStrings()
        {
            // basic construction
            DerBitString s1 = new DerBitString(new byte[0], 0);

            // check GetBytes()
            s1.GetBytes();

            // check encoding/decoding
            DerBitString derBit = (DerBitString)Asn1Object.FromByteArray(s1.GetEncoded());

            if (!Arrays.AreEqual(s1.GetEncoded(), Hex.Decode("030100")))
            {
                Fail("zero encoding wrong");
            }

            try
            {
                new DerBitString(null, 1);
                Fail("exception not thrown");
            }
            catch (ArgumentNullException)
            {
            }

            try
            {
                new DerBitString(new byte[0], 1);
                Fail("exception not thrown");
            }
            catch (ArgumentException)
            {
            }

            try
            {
                new DerBitString(new byte[1], 8);
                Fail("exception not thrown");
            }
            catch (ArgumentException)
            {
            }

            DerBitString s2 = new DerBitString(0);

            if (!Arrays.AreEqual(s1.GetEncoded(), s2.GetEncoded()))
            {
                Fail("zero encoding wrong");
            }
        }
Exemplo n.º 5
0
        public X509Certificate(
            X509CertificateStructure c)
        {
            this.c = c;

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));

                if (str != null)
                {
                    basicConstraints = BasicConstraints.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));

                if (str != null)
                {
                    DerBitString bits = DerBitString.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));

                    byte[] bytes  = bits.GetBytes();
                    int    length = (bytes.Length * 8) - bits.PadBits;

                    keyUsage = new bool[(length < 9) ? 9 : length];

                    for (int i = 0; i != length; i++)
                    {
//						keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
                        keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
                    }
                }
                else
                {
                    keyUsage = null;
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct KeyUsage: " + e);
            }
        }
Exemplo n.º 6
0
        private void DoTestZeroLengthStrings()
        {
            // basic construction
            DerBitString s1 = new DerBitString(new byte[0], 0);

            // check GetBytes()
            s1.GetBytes();

            // check encoding/decoding
            DerBitString derBit = (DerBitString)Asn1Object.FromByteArray(s1.GetEncoded());

            if (!Arrays.AreEqual(s1.GetEncoded(), Hex.Decode("030100")))
            {
                Fail("zero encoding wrong");
            }

            try
            {
                new DerBitString(null, 1);
                Fail("exception not thrown");
            }
            catch (ArgumentNullException)
            {
            }

            try
            {
                new DerBitString(new byte[0], 1);
                Fail("exception not thrown");
            }
            catch (ArgumentException)
            {
            }

            try
            {
                new DerBitString(new byte[1], 8);
                Fail("exception not thrown");
            }
            catch (ArgumentException)
            {
            }

            DerBitString s2 = new DerBitString(0);
            if (!Arrays.AreEqual(s1.GetEncoded(), s2.GetEncoded()))
            {
                Fail("zero encoding wrong");
            }
        }
        public virtual bool[] GetIssuerUniqueID()
        {
            DerBitString issuerUniqueID = this.cert.ACInfo.IssuerUniqueID;

            if (issuerUniqueID != null)
            {
                byte[] bytes = issuerUniqueID.GetBytes();
                bool[] array = new bool[bytes.Length * 8 - issuerUniqueID.PadBits];
                for (int num = 0; num != array.Length; num++)
                {
                    array[num] = (((int)bytes[num / 8] & 128 >> num % 8) != 0);
                }
                return(array);
            }
            return(null);
        }
    public virtual bool[] GetIssuerUniqueID()
    {
        DerBitString issuerUniqueID = cert.ACInfo.IssuerUniqueID;

        if (issuerUniqueID != null)
        {
            byte[] bytes = issuerUniqueID.GetBytes();
            bool[] array = new bool[bytes.Length * 8 - issuerUniqueID.PadBits];
            for (int i = 0; i != array.Length; i++)
            {
                array[i] = ((bytes[i / 8] & (128 >> i % 8)) != 0);
            }
            return(array);
        }
        return(null);
    }
Exemplo n.º 9
0
        public static string Encrypt(string stringToBeEncrypted, string stringPublicKey)
        {
            var publicKeySequence = (DerSequence)Asn1Object.FromByteArray(Convert.FromBase64String(stringPublicKey));
            var encodedPublicKey1 = new DerBitString(publicKeySequence[0]);
            var encodedPublicKey2 = new DerBitString(publicKeySequence[1]);
            var modulus           = (DerInteger)Asn1Object.FromByteArray(encodedPublicKey1.GetBytes());
            var exponent          = (DerInteger)Asn1Object.FromByteArray(encodedPublicKey2.GetBytes());
            var y = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
            var x = DotNetUtilities.ToRSAParameters(y);

            using (var provider = new RSACryptoServiceProvider())
            {
                provider.ImportParameters(x);
                var dataToBeEncrypted = Encoding.UTF8.GetBytes(stringToBeEncrypted);
                var bytes             = provider.Encrypt(dataToBeEncrypted, true);
                return(Convert.ToBase64String(bytes));
            }
        }
Exemplo n.º 10
0
        private void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
        {
            X509Extensions exts = c.TbsCertificate.Extensions;

            if (exts != null)
            {
                X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
                if (ext != null)
                {
                    DerBitString ku   = KeyUsage.GetInstance(ext);
                    int          bits = ku.GetBytes()[0];
                    if ((bits & keyUsageBits) != keyUsageBits)
                    {
                        handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown);
                    }
                }
            }
        }
Exemplo n.º 11
0
        internal static void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
        {
            X509Extensions exts = c.TbsCertificate.Extensions;

            if (exts != null)
            {
                X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
                if (ext != null)
                {
                    DerBitString ku   = KeyUsage.GetInstance(ext);
                    int          bits = ku.GetBytes()[0];
                    if ((bits & keyUsageBits) != keyUsageBits)
                    {
                        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                    }
                }
            }
        }
        public virtual bool[] GetIssuerUniqueID()
        {
            DerBitString id = cert.ACInfo.IssuerUniqueID;

            if (id != null)
            {
                byte[] bytes  = id.GetBytes();
                bool[] boolId = new bool[bytes.Length * 8 - id.PadBits];

                for (int i = 0; i != boolId.Length; i++)
                {
                    //boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
                    boolId[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
                }

                return(boolId);
            }

            return(null);
        }
Exemplo n.º 13
0
        private async Task InitConnection()
        {
            OnConnectionEstablished?.Invoke(this, System.EventArgs.Empty);

            var publicKey = await webApi.GetRequest <GetPublicKeyResponse>("jdev/sys/getPublicKey");;

            _pubKey = Convert.FromBase64String(publicKey.Data.PublicKey.Replace("-----END CERTIFICATE-----", "").Replace("-----BEGIN CERTIFICATE-----", ""));
            string stringDataToEncrypt;

            SecureRandom random = new SecureRandom();

            _aesKey = GenerateAesKey(LoxoneUuid);

            _aesIv = new byte[128 / 8];
            random.NextBytes(_aesIv);

            stringDataToEncrypt = $"{_aesKey.ToHex(false)}:{_aesIv.ToHex(false)}";

            Asn1Object  obj = Asn1Object.FromByteArray(_pubKey);
            DerSequence publicKeySequence = (DerSequence)obj;

            DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
            DerSequence  publicKeyDer     = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());

            DerInteger modulus  = (DerInteger)publicKeyDer[0];
            DerInteger exponent = (DerInteger)publicKeyDer[1];

            RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            encryptEngine.Init(true, keyParameters);

            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringDataToEncrypt);
            byte[] encryptedData = encryptEngine.ProcessBlock(dataToEncrypt, 0, dataToEncrypt.Length);

            var publicKeySelf = Convert.ToBase64String(encryptedData);

            _connectionState = ConnectionState.ExchangeKeys;

            _webSocket.Send($"jdev/sys/keyexchange/{publicKeySelf}");
        }
Exemplo n.º 14
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception arg)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + arg);
         IL_004c :;
     }
     try
     {
         Asn1OctetString extensionValue2 = GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             keyUsage = new bool[(num >= 9) ? num : 9];
             for (int i = 0; i != num; i++)
             {
                 keyUsage[i] = ((bytes[i / 8] & (128 >> i % 8)) != 0);
             }
         }
         else
         {
             keyUsage = null;
         }
     }
     catch (Exception arg2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + arg2);
         IL_0108 :;
     }
 }
Exemplo n.º 15
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (global::System.Exception ex)
     {
         throw new CertificateParsingException(string.Concat((object)"cannot construct BasicConstraints: ", (object)ex));
     }
     try
     {
         Asn1OctetString extensionValue2 = GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             keyUsage = new bool[(num < 9) ? 9 : num];
             for (int i = 0; i != num; i++)
             {
                 keyUsage[i] = (bytes[i / 8] & (128 >> i % 8)) != 0;
             }
         }
         else
         {
             keyUsage = null;
         }
     }
     catch (global::System.Exception ex2)
     {
         throw new CertificateParsingException(string.Concat((object)"cannot construct KeyUsage: ", (object)ex2));
     }
 }
Exemplo n.º 16
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             this.basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception exception)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + exception);
     }
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
             byte[]       bytes    = instance.GetBytes();
             int          num      = (bytes.Length * 8) - instance.PadBits;
             this.keyUsage = new bool[(num >= 9) ? num : 9];
             for (int i = 0; i != num; i++)
             {
                 this.keyUsage[i] = (bytes[i / 8] & (((int)0x80) >> (i % 8))) != 0;
             }
         }
         else
         {
             this.keyUsage = null;
         }
     }
     catch (Exception exception2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + exception2);
     }
 }
Exemplo n.º 17
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             this.basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception arg)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + arg);
     }
     try
     {
         Asn1OctetString extensionValue2 = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             this.keyUsage = new bool[(num < 9) ? 9 : num];
             for (int num2 = 0; num2 != num; num2++)
             {
                 this.keyUsage[num2] = (((int)bytes[num2 / 8] & 128 >> num2 % 8) != 0);
             }
         }
         else
         {
             this.keyUsage = null;
         }
     }
     catch (Exception arg2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + arg2);
     }
 }
Exemplo n.º 18
0
        private object ReadPrivateKey(PemObject pemObject)
        {
            string text = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[]      array      = pemObject.Content;
            IDictionary dictionary = Platform.CreateHashtable();

            foreach (PemHeader pemHeader in pemObject.Headers)
            {
                dictionary[pemHeader.Name] = pemHeader.Value;
            }
            string a = (string)dictionary["Proc-Type"];

            if (a == "4,ENCRYPTED")
            {
                if (this.pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }
                char[] password = this.pFinder.GetPassword();
                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }
                string   text2  = (string)dictionary["DEK-Info"];
                string[] array2 = text2.Split(new char[]
                {
                    ','
                });
                string dekAlgName = array2[0].Trim();
                byte[] iv         = Hex.Decode(array2[1].Trim());
                array = PemUtilities.Crypt(false, array, password, dekAlgName, iv);
            }
            object result;

            try
            {
                Asn1Sequence instance = Asn1Sequence.GetInstance(array);
                string       a2;
                if ((a2 = text) != null)
                {
                    AsymmetricKeyParameter asymmetricKeyParameter;
                    AsymmetricKeyParameter publicParameter;
                    if (!(a2 == "RSA"))
                    {
                        if (!(a2 == "DSA"))
                        {
                            if (!(a2 == "EC"))
                            {
                                if (!(a2 == "ENCRYPTED"))
                                {
                                    if (!(a2 == ""))
                                    {
                                        goto IL_356;
                                    }
                                    result = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                                else
                                {
                                    char[] password2 = this.pFinder.GetPassword();
                                    if (password2 == null)
                                    {
                                        throw new PasswordException("Password is null, but a password is required");
                                    }
                                    result = PrivateKeyFactory.DecryptKey(password2, EncryptedPrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                            }
                            else
                            {
                                ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(instance);
                                AlgorithmIdentifier   algID   = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, eCPrivateKeyStructure.GetParameters());
                                PrivateKeyInfo        keyInfo = new PrivateKeyInfo(algID, eCPrivateKeyStructure.ToAsn1Object());
                                asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyInfo);
                                DerBitString publicKey = eCPrivateKeyStructure.GetPublicKey();
                                if (publicKey != null)
                                {
                                    SubjectPublicKeyInfo keyInfo2 = new SubjectPublicKeyInfo(algID, publicKey.GetBytes());
                                    publicParameter = PublicKeyFactory.CreateKey(keyInfo2);
                                }
                                else
                                {
                                    publicParameter = ECKeyPairGenerator.GetCorrespondingPublicKey((ECPrivateKeyParameters)asymmetricKeyParameter);
                                }
                            }
                        }
                        else
                        {
                            if (instance.Count != 6)
                            {
                                throw new PemException("malformed sequence in DSA private key");
                            }
                            DerInteger    derInteger  = (DerInteger)instance[1];
                            DerInteger    derInteger2 = (DerInteger)instance[2];
                            DerInteger    derInteger3 = (DerInteger)instance[3];
                            DerInteger    derInteger4 = (DerInteger)instance[4];
                            DerInteger    derInteger5 = (DerInteger)instance[5];
                            DsaParameters parameters  = new DsaParameters(derInteger.Value, derInteger2.Value, derInteger3.Value);
                            asymmetricKeyParameter = new DsaPrivateKeyParameters(derInteger5.Value, parameters);
                            publicParameter        = new DsaPublicKeyParameters(derInteger4.Value, parameters);
                        }
                    }
                    else
                    {
                        if (instance.Count != 9)
                        {
                            throw new PemException("malformed sequence in RSA private key");
                        }
                        RsaPrivateKeyStructure instance2 = RsaPrivateKeyStructure.GetInstance(instance);
                        publicParameter        = new RsaKeyParameters(false, instance2.Modulus, instance2.PublicExponent);
                        asymmetricKeyParameter = new RsaPrivateCrtKeyParameters(instance2.Modulus, instance2.PublicExponent, instance2.PrivateExponent, instance2.Prime1, instance2.Prime2, instance2.Exponent1, instance2.Exponent2, instance2.Coefficient);
                    }
                    result = new AsymmetricCipherKeyPair(publicParameter, asymmetricKeyParameter);
                    return(result);
                }
IL_356:
                throw new ArgumentException("Unknown key type: " + text, "type");
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (Exception ex2)
            {
                throw new PemException("problem creating " + text + " private key: " + ex2.ToString());
            }
            return(result);
        }
Exemplo n.º 19
0
 private static void AsString(string indent, bool verbose, Asn1Object obj, StringBuilder buf)
 {
     if (obj is Asn1Sequence)
     {
         string text = indent + "    ";
         buf.Append(indent);
         if (obj is BerSequence)
         {
             buf.Append("BER Sequence");
         }
         else if (obj is DerSequence)
         {
             buf.Append("DER Sequence");
         }
         else
         {
             buf.Append("Sequence");
         }
         buf.Append(NewLine);
         foreach (Asn1Encodable item in (Asn1Sequence)obj)
         {
             if (item == null || item is Asn1Null)
             {
                 buf.Append(text);
                 buf.Append("NULL");
                 buf.Append(NewLine);
             }
             else
             {
                 AsString(text, verbose, item.ToAsn1Object(), buf);
             }
         }
     }
     else if (obj is DerTaggedObject)
     {
         string text2 = indent + "    ";
         buf.Append(indent);
         if (obj is BerTaggedObject)
         {
             buf.Append("BER Tagged [");
         }
         else
         {
             buf.Append("Tagged [");
         }
         DerTaggedObject derTaggedObject = (DerTaggedObject)obj;
         buf.Append(derTaggedObject.TagNo.ToString());
         buf.Append(']');
         if (!derTaggedObject.IsExplicit())
         {
             buf.Append(" IMPLICIT ");
         }
         buf.Append(NewLine);
         if (derTaggedObject.IsEmpty())
         {
             buf.Append(text2);
             buf.Append("EMPTY");
             buf.Append(NewLine);
         }
         else
         {
             AsString(text2, verbose, derTaggedObject.GetObject(), buf);
         }
     }
     else if (obj is BerSet)
     {
         string text3 = indent + "    ";
         buf.Append(indent);
         buf.Append("BER Set");
         buf.Append(NewLine);
         foreach (Asn1Encodable item2 in (Asn1Set)obj)
         {
             if (item2 == null)
             {
                 buf.Append(text3);
                 buf.Append("NULL");
                 buf.Append(NewLine);
             }
             else
             {
                 AsString(text3, verbose, item2.ToAsn1Object(), buf);
             }
         }
     }
     else if (obj is DerSet)
     {
         string text4 = indent + "    ";
         buf.Append(indent);
         buf.Append("DER Set");
         buf.Append(NewLine);
         foreach (Asn1Encodable item3 in (Asn1Set)obj)
         {
             if (item3 == null)
             {
                 buf.Append(text4);
                 buf.Append("NULL");
                 buf.Append(NewLine);
             }
             else
             {
                 AsString(text4, verbose, item3.ToAsn1Object(), buf);
             }
         }
     }
     else if (obj is DerObjectIdentifier)
     {
         buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
     }
     else if (obj is DerBoolean)
     {
         buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
     }
     else if (obj is DerInteger)
     {
         buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
     }
     else if (obj is BerOctetString)
     {
         byte[] octets = ((Asn1OctetString)obj).GetOctets();
         string text5  = verbose ? dumpBinaryDataAsString(indent, octets) : "";
         buf.Append(indent + "BER Octet String[" + octets.Length + "] " + text5 + NewLine);
     }
     else if (obj is DerOctetString)
     {
         byte[] octets2 = ((Asn1OctetString)obj).GetOctets();
         string text6   = verbose ? dumpBinaryDataAsString(indent, octets2) : "";
         buf.Append(indent + "DER Octet String[" + octets2.Length + "] " + text6 + NewLine);
     }
     else if (obj is DerBitString)
     {
         DerBitString derBitString = (DerBitString)obj;
         byte[]       bytes        = derBitString.GetBytes();
         string       text7        = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
         buf.Append(indent + "DER Bit String[" + bytes.Length + ", " + derBitString.PadBits + "] " + text7 + NewLine);
     }
     else if (obj is DerIA5String)
     {
         buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerUtf8String)
     {
         buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerPrintableString)
     {
         buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerVisibleString)
     {
         buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerBmpString)
     {
         buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerT61String)
     {
         buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerGraphicString)
     {
         buf.Append(indent + "GraphicString(" + ((DerGraphicString)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerVideotexString)
     {
         buf.Append(indent + "VideotexString(" + ((DerVideotexString)obj).GetString() + ") " + NewLine);
     }
     else if (obj is DerUtcTime)
     {
         buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
     }
     else if (obj is DerGeneralizedTime)
     {
         buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
     }
     else if (obj is BerApplicationSpecific)
     {
         buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
     }
     else if (obj is DerApplicationSpecific)
     {
         buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
     }
     else if (obj is DerEnumerated)
     {
         DerEnumerated derEnumerated = (DerEnumerated)obj;
         buf.Append(indent + "DER Enumerated(" + derEnumerated.Value + ")" + NewLine);
     }
     else if (obj is DerExternal)
     {
         DerExternal derExternal = (DerExternal)obj;
         buf.Append(indent + "External " + NewLine);
         string text8 = indent + "    ";
         if (derExternal.DirectReference != null)
         {
             buf.Append(text8 + "Direct Reference: " + derExternal.DirectReference.Id + NewLine);
         }
         if (derExternal.IndirectReference != null)
         {
             buf.Append(text8 + "Indirect Reference: " + derExternal.IndirectReference.ToString() + NewLine);
         }
         if (derExternal.DataValueDescriptor != null)
         {
             AsString(text8, verbose, derExternal.DataValueDescriptor, buf);
         }
         buf.Append(text8 + "Encoding: " + derExternal.Encoding + NewLine);
         AsString(text8, verbose, derExternal.ExternalContent, buf);
     }
     else
     {
         buf.Append(indent + obj.ToString() + NewLine);
     }
 }
Exemplo n.º 20
0
 /**
  * for when the public key is an encoded object - if the bitstring
  * can't be decoded this routine raises an IOException.
  *
  * @exception IOException - if the bit string doesn't represent a Der
  * encoded object.
  */
 public Asn1Object GetPublicKey()
 {
     return(Asn1Object.FromByteArray(keyData.GetBytes()));
 }
Exemplo n.º 21
0
 public PkiFailureInfo(
     DerBitString info)
     : base(info.GetBytes(), info.PadBits)
 {
 }
Exemplo n.º 22
0
 public ReasonFlags(
     DerBitString reasons)
     : base(reasons.GetBytes(), reasons.PadBits)
 {
 }
Exemplo n.º 23
0
 private KeyUsage(
     DerBitString usage)
     : base(usage.GetBytes(), usage.PadBits)
 {
 }
Exemplo n.º 24
0
 public ReasonFlags(int reasons)
     : base(DerBitString.GetBytes(reasons), DerBitString.GetPadBits(reasons))
 {
 }
Exemplo n.º 25
0
        private void AddAsn1Object(string name, DataKey root, Asn1Object obj, int level, Logger logger)
        {
            Asn1Sequence     seq      = obj as Asn1Sequence;
            Asn1Set          set      = obj as Asn1Set;
            Asn1TaggedObject tag      = obj as Asn1TaggedObject;
            string           currName = name ?? obj.GetType().Name;

            System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", currName, obj.GetType()));

            if (seq != null)
            {
                if (!Config.IgnoreSequences)
                {
                    DataKey key = new Asn1SequenceKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in seq)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (set != null)
            {
                if (!Config.IgnoreSets)
                {
                    DataKey key = new Asn1SetKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in set)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (tag != null)
            {
                if (!Config.IgnoreTaggedObjects)
                {
                    DataKey key = new Asn1TaggedObjectKey(currName, tag.TagNo, Config.NoVerify);

                    root.AddSubNode(key);

                    Asn1Object     o   = tag.GetObject();
                    DerOctetString oct = o as DerOctetString;

                    AddAsn1Object("Object", key, tag.GetObject(), level + 1, logger);

                    //if (oct != null)
                    //{
                    //    Asn1InputStream input = new Asn1InputStream(oct.GetOctetStream());

                    //    try
                    //    {
                    //        Asn1Object next = input.ReadObject();
                    //        if (next == null)
                    //        {
                    //            AddAsn1Object("Object", key, o, logger);
                    //        }
                    //        else
                    //        {
                    //            Asn1OctetStringObject newRoot = new Asn1OctetStringObject("Object");

                    //            while (next != null)
                    //            {
                    //                AddAsn1Object(next.GetType().Name, newRoot, next, logger);

                    //                next = input.ReadObject();
                    //            }

                    //            key.AddSubNode(newRoot);
                    //        }
                    //    }
                    //    catch (IOException)
                    //    {
                    //        AddAsn1Object("Object", key, o, logger);
                    //    }
                    //}
                    //else
                    //{
                    //    AddAsn1Object("Object", key, tag.GetObject(), logger);
                    //}
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else
            {
                if (!Config.NoDecode)
                {
                    DerStringBase          str  = obj as DerStringBase;
                    DerObjectIdentifier    oid  = obj as DerObjectIdentifier;
                    DerInteger             i    = obj as DerInteger;
                    DerOctetString         oct  = obj as DerOctetString;
                    DerBitString           bits = obj as DerBitString;
                    DerBoolean             boo  = obj as DerBoolean;
                    DerNull                n    = obj as DerNull;
                    DerUtcTime             time = obj as DerUtcTime;
                    DerGeneralizedTime     gt   = obj as DerGeneralizedTime;
                    DerApplicationSpecific app  = obj as DerApplicationSpecific;

                    if (oct != null)
                    {
                        root.AddValue(new Asn1OctetStringValue(currName, oct.GetOctets()));
                    }
                    else if (bits != null)
                    {
                        root.AddSubNode(new Asn1BitStringKey(currName, bits.PadBits, bits.GetBytes()));
                    }
                    else if (str != null)
                    {
                        Type stringType = typeof(Asn1StringValue <>).MakeGenericType(str.GetType());

                        root.AddValue((DataValue)Activator.CreateInstance(stringType, currName, str.GetString()));
                    }
                    else if (oid != null)
                    {
                        root.AddValue(new Asn1ObjectIdentifierValue(currName, oid.Id));
                    }
                    else if (i != null)
                    {
                        root.AddValue(new Asn1IntegerValue(currName, i.Value.ToByteArray()));
                    }
                    else if (boo != null)
                    {
                        root.AddValue(new Asn1BooleanValue(currName, boo.IsTrue));
                    }
                    else if (n != null)
                    {
                        root.AddValue(new Asn1NullValue(currName));
                    }
                    else if (time != null)
                    {
                        root.AddValue(new Asn1DateTimeValue(currName, time.ToDateTime()));
                    }
                    else if (gt != null)
                    {
                        root.AddValue(new Asn1GeneralizedTimeValue(currName, gt.ToDateTime()));
                    }
                    else if (app != null)
                    {
                        root.AddSubNode(new Asn1ApplicationSpecificValue(currName, app.ApplicationTag, app.GetContents()));
                    }
                    else
                    {
                        logger.LogError("Cannot convert type {0} to a class", obj.GetType().Name);
                        root.AddValue(currName, obj.GetDerEncoded());
                    }
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
        }
Exemplo n.º 26
0
		public PkiFailureInfo(
			DerBitString info)
			:	base(info.GetBytes(), info.PadBits)
		{
		}
Exemplo n.º 27
0
        public X509Certificate(
            X509CertificateStructure c)
        {
            this.c = c;

            try
            {
                this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);

                Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
                this.sigAlgParams = (null == parameters) ? null : parameters.GetEncoded(Asn1Encodable.Der);
            }
            catch (Exception e)
            {
                throw new CrlException("Certificate contents invalid: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));

                if (str != null)
                {
                    basicConstraints = BasicConstraints.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));

                if (str != null)
                {
                    DerBitString bits = DerBitString.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));

                    byte[] bytes  = bits.GetBytes();
                    int    length = (bytes.Length * 8) - bits.PadBits;

                    keyUsage = new bool[(length < 9) ? 9 : length];

                    for (int i = 0; i != length; i++)
                    {
//						keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
                        keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
                    }
                }
                else
                {
                    keyUsage = null;
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct KeyUsage: " + e);
            }
        }
Exemplo n.º 28
0
		public ReasonFlags(
            DerBitString reasons)
             : base(reasons.GetBytes(), reasons.PadBits)
        {
        }
Exemplo n.º 29
0
        /**
         * dump a Der object as a formatted string with indentation
         *
         * @param obj the Asn1Object to be dumped out.
         */
        private static void AsString(
            string indent,
            bool verbose,
            Asn1Object obj,
            StringBuilder buf)
        {
            if (obj is Asn1Sequence)
            {
                string tab = indent + Tab;
                buf.Append(indent);
                if (obj is BerSequence)
                {
                    buf.Append("BER Sequence");
                }
                else if (obj is DerSequence)
                {
                    buf.Append("DER Sequence");
                }
                else
                {
                    buf.Append("Sequence");
                }

                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Sequence)obj))
                {
                    if (o == null || o is Asn1Null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerTaggedObject)
            {
                string tab = indent + Tab;
                buf.Append(indent);
                if (obj is BerTaggedObject)
                {
                    buf.Append("BER Tagged [");
                }
                else
                {
                    buf.Append("Tagged [");
                }

                DerTaggedObject o = (DerTaggedObject)obj;

                buf.Append(((int)o.TagNo).ToString());
                buf.Append(']');

                if (!o.IsExplicit())
                {
                    buf.Append(" IMPLICIT ");
                }

                buf.Append(NewLine);

                if (o.IsEmpty())
                {
                    buf.Append(tab);
                    buf.Append("EMPTY");
                    buf.Append(NewLine);
                }
                else
                {
                    AsString(tab, verbose, o.GetObject(), buf);
                }
            }
            else if (obj is BerSet)
            {
                string tab = indent + Tab;

                buf.Append(indent);
                buf.Append("BER Set");
                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerSet)
            {
                string tab = indent + Tab;

                buf.Append(indent);
                buf.Append("DER Set");
                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerObjectIdentifier)
            {
                buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
            }
            else if (obj is DerBoolean)
            {
                buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
            }
            else if (obj is DerInteger)
            {
                buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
            }
            else if (obj is BerOctetString)
            {
                byte[] octets = ((Asn1OctetString)obj).GetOctets();
                string extra  = verbose ? dumpBinaryDataAsString(indent, octets) : "";
                buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
            }
            else if (obj is DerOctetString)
            {
                byte[] octets = ((Asn1OctetString)obj).GetOctets();
                string extra  = verbose ? dumpBinaryDataAsString(indent, octets) : "";
                buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
            }
            else if (obj is DerBitString)
            {
                DerBitString bt    = (DerBitString)obj;
                byte[]       bytes = bt.GetBytes();
                string       extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
                buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine);
            }
            else if (obj is DerIA5String)
            {
                buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerUtf8String)
            {
                buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerPrintableString)
            {
                buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerVisibleString)
            {
                buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerBmpString)
            {
                buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerT61String)
            {
                buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerUtcTime)
            {
                buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
            }
            else if (obj is DerGeneralizedTime)
            {
                buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
            }
            else if (obj is DerUnknownTag)
            {
                string hex = Hex.ToHexString(((DerUnknownTag)obj).GetData());
                buf.Append(indent + "Unknown " + ((int)((DerUnknownTag)obj).Tag).ToString("X") + " " + hex + NewLine);
            }
            else if (obj is BerApplicationSpecific)
            {
                buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
            }
            else if (obj is DerApplicationSpecific)
            {
                buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
            }
            else if (obj is DerEnumerated)
            {
                DerEnumerated en = (DerEnumerated)obj;
                buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine);
            }
            else if (obj is DerExternal)
            {
                DerExternal ext = (DerExternal)obj;
                buf.Append(indent + "External " + NewLine);
                string tab = indent + Tab;

                if (ext.DirectReference != null)
                {
                    buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine);
                }
                if (ext.IndirectReference != null)
                {
                    buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine);
                }
                if (ext.DataValueDescriptor != null)
                {
                    AsString(tab, verbose, ext.DataValueDescriptor, buf);
                }
                buf.Append(tab + "Encoding: " + ext.Encoding + NewLine);
                AsString(tab, verbose, ext.ExternalContent, buf);
            }
            else
            {
                buf.Append(indent + obj.ToString() + NewLine);
            }
        }
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                {
                    return(ReadPkcsDHParam(algOid, y, seq));
                }

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation        = null;
                DHValidationParms      dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[]     seed        = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(ReadPkcsDHParam(algOid, derY.Value, seq));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(
                    algID.Parameters.ToAsn1Object());
                X9ECParameters ecP;

                if (para.IsNamedCurve)
                {
                    ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    ecP = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECDomainParameters dParams = new ECDomainParameters(
                    ecP.Curve,
                    ecP.G,
                    ecP.N,
                    ecP.H,
                    ecP.GetSeed());

                DerBitString    bits = keyInfo.PublicKeyData;
                byte[]          data = bits.GetBytes();
                Asn1OctetString key  = new DerOctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.Curve, key);

                return(new ECPublicKeyParameters(derQ.Point, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x      = new byte[32];
                byte[] y      = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false);

                return(new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
Exemplo n.º 31
0
 public NetscapeCertType(DerBitString usage)
     : base(usage.GetBytes(), usage.PadBits)
 {
 }
Exemplo n.º 32
0
        /**
         * Read a Key Pair
         */
        private object ReadPrivateKey(PemObject pemObject)
        {
            //
            // extract the key
            //
            Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY"));

            string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[] keyBytes = pemObject.Content;

            IDictionary fields = Platform.CreateHashtable();

            foreach (PemHeader header in pemObject.Headers)
            {
                fields[header.Name] = header.Value;
            }

            string procType = (string)fields["Proc-Type"];

            if (procType == "4,ENCRYPTED")
            {
                if (pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }

                char[] password = pFinder.GetPassword();

                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }

                string   dekInfo = (string)fields["DEK-Info"];
                string[] tknz    = dekInfo.Split(',');

                string dekAlgName = tknz[0].Trim();
                byte[] iv         = Hex.Decode(tknz[1].Trim());

                keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
            }

            try
            {
                AsymmetricKeyParameter pubSpec, privSpec;
                Asn1Sequence           seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes);

                switch (type)
                {
                case "RSA":
                {
                    if (seq.Count != 9)
                    {
                        throw new PemException("malformed sequence in RSA private key");
                    }

                    RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);

                    pubSpec  = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
                    privSpec = new RsaPrivateCrtKeyParameters(
                        rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                        rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                        rsa.Coefficient);

                    break;
                }

                case "DSA":
                {
                    if (seq.Count != 6)
                    {
                        throw new PemException("malformed sequence in DSA private key");
                    }

                    // TODO Create an ASN1 object somewhere for this?
                    //DerInteger v = (DerInteger)seq[0];
                    DerInteger p = (DerInteger)seq[1];
                    DerInteger q = (DerInteger)seq[2];
                    DerInteger g = (DerInteger)seq[3];
                    DerInteger y = (DerInteger)seq[4];
                    DerInteger x = (DerInteger)seq[5];

                    DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

                    privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
                    pubSpec  = new DsaPublicKeyParameters(y.Value, parameters);

                    break;
                }

                case "EC":
                {
                    ECPrivateKeyStructure pKey  = new ECPrivateKeyStructure(seq);
                    AlgorithmIdentifier   algId = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                    PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

                    // TODO Are the keys returned here ECDSA, as Java version forces?
                    privSpec = PrivateKeyFactory.CreateKey(privInfo);

                    DerBitString pubKey = pKey.GetPublicKey();
                    if (pubKey != null)
                    {
                        SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

                        // TODO Are the keys returned here ECDSA, as Java version forces?
                        pubSpec = PublicKeyFactory.CreateKey(pubInfo);
                    }
                    else
                    {
                        pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
                            (ECPrivateKeyParameters)privSpec);
                    }

                    break;
                }

                case "ENCRYPTED":
                {
                    char[] password = pFinder.GetPassword();

                    if (password == null)
                    {
                        throw new PasswordException("Password is null, but a password is required");
                    }

                    return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq)));
                }

                case "":
                {
                    return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq)));
                }

                default:
                    throw new ArgumentException("Unknown key type: " + type, "type");
                }

                return(new AsymmetricCipherKeyPair(pubSpec, privSpec));
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new PemException(
                          "problem creating " + type + " private key: " + e.ToString());
            }
        }
Exemplo n.º 33
0
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement) ||
                     algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPublicKeyParameters(derY.Value, dhParams));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(
                    algID.Parameters.ToAsn1Object());
                X9ECParameters ecP;

                if (para.IsNamedCurve)
                {
                    // TODO ECGost3410NamedCurves support (returns ECDomainParameters though)

                    DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters;
                    ecP = X962NamedCurves.GetByOid(oid);

                    if (ecP == null)
                    {
                        ecP = SecNamedCurves.GetByOid(oid);

                        if (ecP == null)
                        {
                            ecP = NistNamedCurves.GetByOid(oid);

                            if (ecP == null)
                            {
                                ecP = TeleTrusTNamedCurves.GetByOid(oid);
                            }
                        }
                    }
                }
                else
                {
                    ecP = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECDomainParameters dParams = new ECDomainParameters(
                    ecP.Curve,
                    ecP.G,
                    ecP.N,
                    ecP.H,
                    ecP.GetSeed());

                DerBitString    bits = keyInfo.PublicKeyData;
                byte[]          data = bits.GetBytes();
                Asn1OctetString key  = new DerOctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.Curve, key);

                return(new ECPublicKeyParameters(derQ.Point, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x      = new byte[32];
                byte[] y      = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false);

                return(new ECPublicKeyParameters(q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
Exemplo n.º 34
0
		private KeyUsage(
			DerBitString usage)
			: base(usage.GetBytes(), usage.PadBits)
        {
        }