ReadObject() public method

public ReadObject ( ) : object
return object
Ejemplo n.º 1
2
        static CmsSignedData ReadPem(String filename)
        {
            StreamReader sR = new StreamReader(filename);
            PemReader pR = new PemReader(sR);

            Org.BouncyCastle.Asn1.Cms.ContentInfo cI = (Org.BouncyCastle.Asn1.Cms.ContentInfo) pR.ReadObject();

            sR.Close();

            CmsSignedData cms = new CmsSignedData(cI);

            return cms;
        }
Ejemplo n.º 2
0
 public static AsymmetricKeyParameter ReadRSAPublicKey(string Path)
 {
     try
     {
         string FileName = System.IO.Path.GetFileNameWithoutExtension(Path);
         if (FileName.Contains("_public"))
         {
             RsaKeyParameters RSAKey;
             TextReader tr = new StreamReader(Path);
             PemReader pr = new PemReader(tr);
             RSAKey = (RsaKeyParameters)pr.ReadObject();
             AsymmetricKeyParameter Key = (AsymmetricKeyParameter)RSAKey;
             pr.Reader.Close();
             tr.Close();
             return Key;
         }
         else
         {
             return null;
         }
     }
     catch (InvalidCastException e)
     {
         return null;
     }
 }
Ejemplo n.º 3
0
        private static X509Certificate LoadCert(string pemData, out AsymmetricKeyParameter privateKey)
        {
            X509Certificate cert = null;

            privateKey = null;
            using (var reader = new StringReader(pemData))
            {
                var    pemReader = new OpenSsl.PemReader(reader);
                object pemObject = null;
                while ((pemObject = pemReader.ReadObject()) != null)
                {
                    if (pemObject is X509Certificate)
                    {
                        cert = pemObject as X509Certificate;
                    }
                    else if (pemObject is AsymmetricCipherKeyPair)
                    {
                        privateKey = (pemObject as AsymmetricCipherKeyPair).Private;
                    }
                }
            }
            if (cert == null)
            {
                throw new System.Security.SecurityException("Certificate could not be loaded from PEM data.");
            }

            if (privateKey == null)
            {
                throw new System.Security.SecurityException("Private Key could not be loaded from PEM data.");
            }

            return(cert);
        }
Ejemplo n.º 4
0
 public static AsymmetricKeyParameter ReadRSAPrivateKey(string Path)
 {
     try
     {
         string FileName = System.IO.Path.GetFileNameWithoutExtension(Path);
         if (FileName.Contains("_private"))
         {
             AsymmetricCipherKeyPair Key;
             TextReader tr = new StreamReader(Path);
             PemReader pr = new PemReader(tr);
             Key = (AsymmetricCipherKeyPair)pr.ReadObject();
             pr.Reader.Close();
             tr.Close();
             return Key.Private;
         }
         else
         {
             return null;
         }
     }
     catch (InvalidCastException e)
     {
         return null;
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Uses RSA Publickey to Ecrypt
        /// Requires .pem file
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns>Cypherbasestring</returns>
        protected internal static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(
                File.OpenText(Program.tempDirectory + "\\IAPubkey.pem")
                );
            RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();


            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            // Pure mathematical RSA implementation
            int         length          = plainTextBytes.Length;
            int         blockSize       = eng.GetInputBlockSize();
            List <byte> cipherTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                cipherTextBytes.AddRange(eng.ProcessBlock(
                                             plainTextBytes, chunkPosition, chunkSize
                                             ));
            }
            return(Convert.ToBase64String(cipherTextBytes.ToArray()));
        }
Ejemplo n.º 6
0
        public override object Deserialize(Stream aStream)
        {
            /* check for required parameters */
              if (aStream == null) {
            throw new ArgumentNullException("aStream");
              }
              PasswordFinder pwFinder = null;
              if (GetPassphraseCallbackMethod != null) {
            pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
              }
              try {
            StreamReader streamReader = new StreamReader(aStream);
            PemReader reader = new PemReader(streamReader, pwFinder);
            object data = reader.ReadObject();

            if (data is AsymmetricCipherKeyPair) {
              return new SshKey(SshVersion.SSH2, (AsymmetricCipherKeyPair)data);
            } else {
              throw new KeyFormatterException("bad data");
            }
              } catch (PasswordException ex) {
            if (GetPassphraseCallbackMethod == null) {
              throw new CallbackNullException();
            }
            throw new KeyFormatterException("see inner exception", ex);
              } catch (KeyFormatterException) {
            throw;
              } catch (Exception ex) {
            throw new KeyFormatterException("see inner exception", ex);
              }
        }
 /// <summary>
 /// Loads a CSR from disk into a <see cref="Pkcs10CertificationRequest"/>
 /// </summary>
 /// <param name="fileName">Path to the CSR file</param>
 /// <returns><see cref="Pkcs10CertificationRequest"/></returns>
 public static Pkcs10CertificationRequest LoadCSR(string fileName)
 {
     using (TextReader tr = File.OpenText(fileName))
     {
         PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(tr);
         return(pr.ReadObject() as Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest);
     }
 }
        internal AsymmetricCipherKeyPair GetKeyPair(string key)
        {
            var reader = new StringReader(key);
            var pem = new PemReader(reader);
            var o = pem.ReadObject();

            return (AsymmetricCipherKeyPair)o;
        }
Ejemplo n.º 9
0
		static DkimTests ()
		{
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "example.pem"))) {
				var reader = new PemReader (stream);

				DkimKeys = reader.ReadObject () as AsymmetricCipherKeyPair;
			}
		}
Ejemplo n.º 10
0
 /// <summary>
 /// Extension to convert a string representing a base64 encoded <see cref="Pkcs10CertificationRequest"/> into a
 /// <see cref="Pkcs10CertificationRequest"/>
 /// </summary>
 /// <param name="csr">String representing a base64 encoded <see cref="Pkcs10CertificationRequest"/></param>
 /// <returns><see cref="Pkcs10CertificationRequest"/></returns>
 public static Pkcs10CertificationRequest ToPkcs10CertificationRequest(this string csr)
 {
     using (TextReader tr = new StringReader(csr))
     {
         PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(tr);
         return(pr.ReadObject() as Pkcs10CertificationRequest);
     }
 }
Ejemplo n.º 11
0
        public static AsymmetricCipherKeyPair ReadAsymmetricKeyParameter(string pemFilename)
        {
            var fileStream   = System.IO.File.OpenText(pemFilename);
            var pemReader    = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
            var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)pemReader.ReadObject();

            return(KeyParameter);
        }
        public override byte[] SignData(ProtocolVersion version, byte[] data, HashAlgorithm hashAlgorithm, CertificatePrivateKey privateKey)
        {
            var ms = new MemoryStream(privateKey.KeyValue);
            var pemReader = new PemReader(new StreamReader(ms));
            var keyParam = pemReader.ReadObject();
            var key = keyParam as AsymmetricCipherKeyPair;
            
            var signer = new ECDsaSigner();
            signer.Init(true, key.Private);
            var hashedData = hashAlgorithm.ComputeHash(data);
            Log.Trace("Hashing data (S):" + BitConverter.ToString(data));
            Log.Trace("Hashed data (S):" + BitConverter.ToString(hashedData));

            var sig = signer.GenerateSignature(hashedData);
            
            // test verify
            var _tmpEcPubkey = key.Public as ECPublicKeyParameters;
            Log.Debug("Associated PubKey Q: " + BitConverter.ToString(_tmpEcPubkey.Q.GetEncoded()));
            var signerTest = new ECDsaSigner();
            signerTest.Init(false, key.Public);
            var result = signerTest.VerifySignature(hashedData, sig[0], sig[1]);
            if (!result)
            {
                throw new CryptographicUnexpectedOperationException("Invalid!!!");
            }

            Log.Debug("R value: " + sig[0].SignValue + " " + sig[0].LongValue);
            Log.Debug("S value: " + sig[1].SignValue + " " + sig[1].LongValue);
            // TODO: check how BigIntegers are encoded before sent over the wire
            // Maybe DER encoding of R and S as integer would do it. However for the moment it works with stuffing 0x00 in.
            var rl = new List<byte>(sig[0].ToByteArray());
            var sl = new List<byte>(sig[1].ToByteArray());
            while (rl.Count < 33)
            {
                rl.Insert(0, 0x00);
            }

            while (sl.Count < 33)
            {
                sl.Insert(0, 0x00);
            }
            var r = rl.ToArray();
            var s = sl.ToArray();
            var rs = new byte[r.Length + s.Length];
            Buffer.BlockCopy(r, 0, rs, 0, r.Length);
            Buffer.BlockCopy(s, 0, rs, r.Length, s.Length);
            
            var derSig = DEREncodeSignature(rs);
            // Log.Debug("DER Signature (S): " + BitConverter.ToString(derSig));
            Log.Trace("Signature R (S)" + BitConverter.ToString(r));
            Log.Trace("Signature S (S)" + BitConverter.ToString(s));
            return derSig;
        }
Ejemplo n.º 13
0
Archivo: RSA.cs Proyecto: Riul/emulator
        public static byte[] Decrypt(byte[] buffer)
        {
            using (TextReader sr = new StringReader(PRIVATE_KEY))
            {
                PemReader pemReader = new PemReader(sr);
                AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;
                IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());

                cipher.Init(false, privateKey);
                return cipher.ProcessBlock(buffer, 0, buffer.Length);
            }
        }
        public override CertificatePrivateKey ImportPrivateKey(byte[] keyData)
        {
            var ms = new MemoryStream(keyData);
            var pemReader = new PemReader(new StreamReader(ms));
            var keyParam = pemReader.ReadObject();
            var kp = keyParam as AsymmetricCipherKeyPair;
            if (kp?.Private == null)
            {
                throw new NullReferenceException();
            }

            Log.Debug("--- ImportedPrivateKey type: {0}", keyParam.GetType());

            return new CertificatePrivateKey(this.CertificateKeyAlgorithm, keyData);
        }
Ejemplo n.º 15
0
		static DkimTests ()
		{
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "example.pem"))) {
				var reader = new PemReader (stream);

				DkimKeys = reader.ReadObject () as AsymmetricCipherKeyPair;
			}

			// Note: you can use http://dkimcore.org/tools/dkimrecordcheck.html to get public keys manually
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "gmail.pub"))) {
				var reader = new PemReader (stream);

				GMailDkimPublicKey = reader.ReadObject () as AsymmetricKeyParameter;
			}
		}
Ejemplo n.º 16
0
    public bool doLoadWallet(string thisFile)
    {
        string theWalletJSON = File.ReadAllText(thisFile);
        Console.Out.WriteLine(theWalletJSON);
        Wallet = JsonConvert.DeserializeObject<Dictionary<string, string>>(theWalletJSON);
        Byte[] bKey = Convert.FromBase64String(Wallet["private_key"]);

        // much like java - the built in crypto doesn't work and looks like it was written by and intern
        // you MUST use bouncycastle - dont even try to use the microsoft lib
        String thePEM = Wallet["pem"];
        var reader = new StringReader(thePEM);
        PemReader pr = new PemReader(reader);
        keyPair = (AsymmetricCipherKeyPair)pr.ReadObject();

        return true;
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Pem密钥转RSA密钥
        /// </summary>
        /// <param name="pemKey">Pem密钥</param>
        /// <param name="isPrivateKey">是否是私钥</param>
        /// <returns>RSA密钥</returns>
        public static string PemToRSAKey(string pemKey, bool isPrivateKey)
        {
            string        rsaKey    = string.Empty;
            object        pemObject = null;
            RSAParameters rsaPara   = new RSAParameters();

            using (StringReader sReader = new StringReader(pemKey))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader);
                pemObject = pemReader.ReadObject();
            }
            //RSA私钥
            if (isPrivateKey)
            {
                RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)pemObject).Private;
                rsaPara = new RSAParameters
                {
                    Modulus  = key.Modulus.ToByteArrayUnsigned(),
                    Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                    D        = key.Exponent.ToByteArrayUnsigned(),
                    P        = key.P.ToByteArrayUnsigned(),
                    Q        = key.Q.ToByteArrayUnsigned(),
                    DP       = key.DP.ToByteArrayUnsigned(),
                    DQ       = key.DQ.ToByteArrayUnsigned(),
                    InverseQ = key.QInv.ToByteArrayUnsigned(),
                };
            }
            //RSA公钥
            else
            {
                RsaKeyParameters key = (RsaKeyParameters)pemObject;
                rsaPara = new RSAParameters
                {
                    Modulus  = key.Modulus.ToByteArrayUnsigned(),
                    Exponent = key.Exponent.ToByteArrayUnsigned(),
                };
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(rsaPara);
            using (StringWriter sw = new StringWriter())
            {
                sw.Write(rsa.ToXmlString(isPrivateKey ? true : false));
                rsaKey = sw.ToString();
            }
            return(rsaKey);
        }
        /// <summary>
        /// Create a certificate for the given onboarding response from the AR.
        /// </summary>
        /// <param name="onboardResponse">-</param>
        /// <returns>A X509 certificate to use for the communication between endpoint and AR.</returns>
        /// <exception cref="CouldNotCreateCertificateForTypeException">-</exception>
        public static X509Certificate GetCertificate(OnboardResponse onboardResponse)
        {
            switch (onboardResponse.Authentication.Type)
            {
            case "P12":
                return(new X509Certificate2(
                           Convert.FromBase64String(onboardResponse.Authentication.Certificate),
                           onboardResponse.Authentication.Secret));

            case "PEM":
            {
                var pemReader = new PemReader(
                    new StringReader(onboardResponse.Authentication.Certificate),
                    new PasswordFinder(onboardResponse.Authentication.Secret));

                RSA privateKey;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    privateKey = ToRSA((RsaPrivateCrtKeyParameters)pemReader.ReadObject());
                }
                else
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        privateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)pemReader.ReadObject());
                    }
                    else
                    {
                        throw new CouldNotCreateCertificateForOsException(
                                  $"Could not create a certificate for '${RuntimeInformation.OSDescription}'");
                    }
                }

                var certificate = pemReader.ReadPemObject();
                if (certificate.Type == "CERTIFICATE")
                {
                    return(new X509Certificate2(certificate.Content).CopyWithPrivateKey(privateKey));
                }

                break;
            }
            }

            throw new CouldNotCreateCertificateForTypeException(
                      $"Could not create a certificate for the type '${onboardResponse.Authentication.Type}'");
        }
Ejemplo n.º 19
0
        public void WczytajPoczatkoweParametry()
        {
            //Wczytywanie klucza prywatnego Sprzedającego
            readerKluczPrywatny = new StreamReader("KluczPrywatnyKlienta.pem");
            pemReaderKluczPrywatny = new PemReader(readerKluczPrywatny);
            keyPairPriv = (AsymmetricCipherKeyPair)pemReaderKluczPrywatny.ReadObject();
            kluczPrywatnyKlienta = keyPairPriv.Private;

            //Wczytywanie klucza publicznego bramy przeznaczonego tylko dla klienta
            readerKluczPublicznyBramyTylkoDlaKlienta = new StreamReader("KluczPublicznyBramyTylkoDlaKlienta.pem");
            pemReaderkluczPublicznyBramyTylkoDlaKlienta = new PemReader(readerKluczPublicznyBramyTylkoDlaKlienta);
            kluczPublicznyBramyTylkoDlaKlienta = (AsymmetricKeyParameter)pemReaderkluczPublicznyBramyTylkoDlaKlienta.ReadObject();

            //Wczytywanie certyfikatu Klienta
            sciezkaCertyfikatuKlienta = "CertyfikatKlienta.crt";
            certyfikatKlienta = new X509Certificate2(sciezkaCertyfikatuKlienta);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Reads the PEM key file and returns the object.
        /// </summary>
        /// <param name="fileName">Path to the pem file</param>
        /// <returns>the read object which may be of different key types</returns>
        /// <exception cref="FormatException">Thrown if the key is not in PEM format</exception>
        private static object ReadPem(string fileName)
        {
            if (!File.Exists(fileName))
                throw new FileNotFoundException("The key file does not exist: " + fileName);

            using (StreamReader file = new StreamReader(fileName))
            {
                PemReader pRd = new PemReader(file);

                object obj = pRd.ReadObject();
                pRd.Reader.Close();
                if (obj == null)
                {
                    throw new FormatException("The key file " + fileName + " is no valid PEM format");
                }
                return obj;
            }
        }
Ejemplo n.º 21
0
        public void Sign(string privateKey)
        {
            string canonicalHeader =
                String.Format(
                    "Method:{0}\nHashed Path:{1}\nX-Ops-Content-Hash:{4}\nX-Ops-Timestamp:{3}\nX-Ops-UserId:{2}",
                    method,
                    requestUri.AbsolutePath.ToBase64EncodedSha1String(),
                    client,
                    timestamp,
                    body.ToBase64EncodedSha1String());

            byte[] input = Encoding.UTF8.GetBytes(canonicalHeader);

            var pemReader = new PemReader(new StringReader(privateKey));
            AsymmetricKeyParameter key = ((AsymmetricCipherKeyPair)pemReader.ReadObject()).Private;

            ISigner signer = new RsaDigestSigner(new NullDigest());
            signer.Init(true, key);
            signer.BlockUpdate(input, 0, input.Length);

            signature = Convert.ToBase64String(signer.GenerateSignature());
        }
Ejemplo n.º 22
0
        public object Decrypt(byte[] pem, byte[] encryptedBytes)
        {
            RsaPrivateCrtKeyParameters privateKey;
            var pemValue = System.Text.Encoding.Default.GetString(pem);

            var reader = new PemReader(new StringReader(pemValue));
            Object obj = reader.ReadObject();
            if (obj is AsymmetricCipherKeyPair)
            {
                privateKey = (RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)obj).Private;
            }
            else
            {
                throw new ArgumentException("'pem' value cannot translate to valid RsaPrivateCrtKeyParameters.");
            }
            RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(privateKey);
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
            rsaKey.ImportParameters(rsaParams);
            // decrypt the value
            var decryptedBytes = rsaKey.Decrypt(encryptedBytes, true);
            Serializer.DeserializeFromByteArray(decryptedBytes);
            return decryptedBytes;
        }
Ejemplo n.º 23
0
    public static string EncodeToken(string uid, Dictionary <string, object> claims)
    {
        // Get the RsaPrivateCrtKeyParameters if we haven't already determined them
        if (_rsaParams == null)
        {
            lock (_rsaParamsLocker)
            {
                if (_rsaParams == null)
                {
                    using (var streamWriter = WriteToStreamWithString(firebasePrivateKey.Replace(@"\n", "\n")))
                    {
                        using (var sr = new StreamReader(streamWriter.BaseStream))
                        {
                            var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                            _rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
                        }
                    }
                }
            }
        }

        var payload = new Dictionary <string, object> {
            { "uid", uid }
            , { "iat", SecondsSinceEpoch(DateTime.UtcNow) }
            , { "exp", SecondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs)) }
            , { "aud", firebasePayloadAUD }
            , { "iss", firebasePayloadISS }
            , { "sub", firebasePayloadSUB }
        };

        if (claims != null && claims.Any())
        {
            payload.Add("claims", claims);
        }

        return(JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256));
    }
Ejemplo n.º 24
0
        private X509Certificate GetSignatureCertChain(Uri uri)
        {
            return ScopingModule.Application.Ensure<X509Certificate>(uri.AbsoluteUri, () =>
            {
                using (var client = new HttpClient())
                {
                    var content = client.GetStringAsync(uri).Result;
                    if (!string.IsNullOrEmpty(content))
                    {
                        var pemReader = new PemReader(new StringReader(content));
                        var cert = (X509Certificate)pemReader.ReadObject();
                        try
                        {
                            cert.CheckValidity();

                            var domainPresent = cert.GetSubjectAlternativeNames()
                                .OfType<ArrayList>()
                                .Any(o => o.OfType<string>().Any(p => p == "echo-api.amazon.com"));

                            if (domainPresent)
                                return cert;
                        }
                        catch (CertificateExpiredException)
                        {
                            return null;
                        }
                        catch (CertificateNotYetValidException)
                        {
                            return null;
                        }
                    }
                }

                return null;
            });
        }
Ejemplo n.º 25
0
	private bool LoadCryptoStuffFromRegistry()
	{
		RegistryKey RKey = Registry.CurrentUser.OpenSubKey("Software\\jPhone\\" + _UniqueDeviceID);
		if (RKey == null) return false;
		if (RKey.GetValue("HostID") == null || RKey.GetValue("RootKey") == null
			|| RKey.GetValue("RootCert") == null || RKey.GetValue("HostKey") == null
			|| RKey.GetValue("HostCert") == null)
		{
			RKey.Close();
			Registry.CurrentUser.DeleteSubKey("Software\\jPhone\\" + _UniqueDeviceID, false);
			return false;
		}

		sHostID = (string)RKey.GetValue("HostID");

		MemoryStream MS;
		TextReader TR;
		Org.BouncyCastle.OpenSsl.PemReader PR;
		byte[] bBuffer;

		bBuffer = (byte[])RKey.GetValue("RootKey");
		MS = new MemoryStream(bBuffer);
		TR = new StreamReader(MS);
		PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
		RootKey = (AsymmetricCipherKeyPair)PR.ReadObject();
		TR.Close();
		MS.Close();

		bBuffer = (byte[])RKey.GetValue("RootCert");
		MS = new MemoryStream(bBuffer);
		TR = new StreamReader(MS);
		PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
		RootCertificate = (Org.BouncyCastle.X509.X509Certificate)PR.ReadObject();
		TR.Close();
		MS.Close();

		bBuffer = (byte[])RKey.GetValue("HostKey");
		MS = new MemoryStream(bBuffer);
		TR = new StreamReader(MS);
		PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
		HostKey = (AsymmetricCipherKeyPair)PR.ReadObject();
		TR.Close();
		MS.Close();

		bBuffer = (byte[])RKey.GetValue("HostCert");
		MS = new MemoryStream(bBuffer);
		TR = new StreamReader(MS);
		PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
		HostCertificate = (Org.BouncyCastle.X509.X509Certificate)PR.ReadObject();
		TR.Close();
		MS.Close();
		
		RKey.Close();
		return true;
	}
Ejemplo n.º 26
0
        private static AsymmetricCipherKeyPair retornaParametrosChavePrivada(string caminhoChavePrivada)
        {
            try
            {
                StreamReader ChavePrivada = System.IO.File.OpenText(caminhoChavePrivada);
                PemReader pemChavePrivada = new PemReader(ChavePrivada);
                AsymmetricCipherKeyPair parametrosChave = (AsymmetricCipherKeyPair)pemChavePrivada.ReadObject();

                return parametrosChave;
            }
            catch (Exception ex)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
        }
Ejemplo n.º 27
0
        public void validate(object sender, EventArgs e)
        {
            string privateKey = privKey.Value;

            string encrypted = RsaEncryptWithPrivate(challenge, privateKey);

            if (encrypted != null)
            {
                try
                {
                    Debug.WriteLine(encrypted);
                    string pubKey         = KeyManager.retrievePublicKey(userID);
                    var    bytesToDecrypt = Convert.FromBase64String(encrypted);
                    var    decryptEngine  = new Pkcs1Encoding(new RsaEngine());
                    var    pKey           = new StringReader(pubKey);
                    Debug.WriteLine(pubKey);
                    var pemReader    = new Org.BouncyCastle.OpenSsl.PemReader(pKey);
                    var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();

                    Debug.WriteLine(bytesToDecrypt.ToString());

                    decryptEngine.Init(false, KeyParameter);
                    Debug.WriteLine(bytesToDecrypt.Length);
                    var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

                    Debug.WriteLine(decrypted);

                    if (decrypted.Equals(challenge))
                    {
                        Response.Redirect("/Admin/Console", false);
                        KeyManager.setLastLogin(userID);
                        Logger.authLogging(DateTime.Now + "," + userID + ",login,success");
                    }
                }
                catch (Exception ex)
                {
                    error.Text = "Invalid Key";
                    Logger.authLogging(DateTime.Now + "," + userID + ",login,failed");
                }
            }
            else
            {
                error.Text = "Wrong Format";
                Logger.authLogging(DateTime.Now + "," + userID + ",login,failed");
            }
        }
Ejemplo n.º 28
0
	public LockdownConnection(iPhoneWrapper IPW) : base(IPW, 0x0A00, 0xF27E)
	{
		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");
		XTW.WriteElementString("key", "Request");
		XTW.WriteElementString("string", "QueryType");
		XTW.WriteEndElement(); // dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		if (!CheckXMLForSuccess(bXMLData))
			throw new Exception("Lockdown hello wasn't successful.");

		#region Get public key
		// Public key is encrypted in base 64.
		string sPublicKey = GetValueFromDevice(null, "DevicePublicKey");

		// Decode sPublicKey from base 64, the result of which looks like
		// "
		// -----BEGIN RSA PUBLIC KEY-----
		// MIGJAoGBAIBNlqucaJt9Q9uX/uYgd5TRYbK4Y3tjMrrkIWThpVL/ry3rTovr9J3b
		// eGaHLUHLU/0ykXB+k7N+li7dOWhOdeAid/k5c5q4UlrOl1+eScsKeR1xUqQD2WMqGL0
		// gsOSstN+38SDOqVxcpP/geTMZsecInrgxv0asbStXdyXdy2DvJaHl2/AgMBAAE=
		// -----END RSA PUBLIC KEY-----
		// "
		byte[] bDecoded = Convert.FromBase64String(sPublicKey);

		// Read the RSA public key into a BouncyCastle structure, to be used in
		// making an X.509 device certificate.
		MS = new MemoryStream(bDecoded);
		TextReader TR = new StreamReader(MS);
		Org.BouncyCastle.OpenSsl.PemReader PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
		DevicePublicKey = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)PR.ReadObject();
		TR.Close();
		MS.Close();
		#endregion
	}
Ejemplo n.º 29
0
		public void TestVerifyGoogleMultipartWithoutEndBoundaryDkimSignature ()
		{
			var message = MimeMessage.Load (Path.Combine ("..", "..", "TestData", "dkim", "multipart-no-end-boundary.msg"));
			int index = message.Headers.IndexOf (HeaderId.DkimSignature);
			AsymmetricKeyParameter key;

			// Note: you can use http://dkimcore.org/tools/dkimrecordcheck.html to get public keys manually
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "gmail.pub"))) {
				var reader = new PemReader (stream);

				key = reader.ReadObject () as AsymmetricKeyParameter;
			}

			Assert.IsTrue (message.Verify (message.Headers[index], new DummyPublicKeyLocator (key)), "Failed to verify GMail signature.");
		}
Ejemplo n.º 30
0
		public static AsymmetricCipherKeyPair importFromPEM(string priv) {
			AsymmetricCipherKeyPair kp;

			using (var textReader = new StringReader (priv)) {
				var pemReader = new PemReader (textReader);
				kp = (AsymmetricCipherKeyPair)pemReader.ReadObject ();
			}

			return kp;
		}
Ejemplo n.º 31
0
		public static AsymmetricKeyParameter importPublicFromPEM(string pub) {
			AsymmetricKeyParameter pubkey;

			using (var textReader = new StringReader (pub)) {
				var pemReader = new PemReader (textReader);
				pubkey = (AsymmetricKeyParameter)pemReader.ReadObject ();
			}

			return pubkey;
		}
Ejemplo n.º 32
0
 private AsymmetricCipherKeyPair readKey1(string filename, string password)
 {
     AsymmetricCipherKeyPair result;
     try
     {
         System.IO.StreamReader sr = new System.IO.StreamReader(filename);
         string file = sr.ReadToEnd();
         sr.Close();
         string privateKey = this.GetStringFromPEM(file, true);
         PemReader pr = new PemReader(new System.IO.StringReader(privateKey), new Certificate.Password(password.ToCharArray()));
         try
         {
             AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
             result = kp;
         }
         catch (System.Exception)
         {
             result = null;
         }
     }
     catch (System.Exception)
     {
         result = null;
     }
     return result;
 }
Ejemplo n.º 33
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DkimSigner"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="DkimSigner"/>.
		/// </remarks>
		/// <param name="fileName">The file containing the private key.</param>
		/// <param name="domain">The domain that the signer represents.</param>
		/// <param name="selector">The selector subdividing the domain.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="fileName"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="domain"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="selector"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="fileName"/> is a zero-length string, contains only white space, or
		/// contains one or more invalid characters as defined by
		/// <see cref="System.IO.Path.InvalidPathChars"/>.
		/// </exception>
		/// <exception cref="System.FormatException">
		/// The file did not contain a private key.
		/// </exception>
		/// <exception cref="System.IO.DirectoryNotFoundException">
		/// <paramref name="fileName"/> is an invalid file path.
		/// </exception>
		/// <exception cref="System.IO.FileNotFoundException">
		/// The specified file path could not be found.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// The user does not have access to read the specified file.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		public DkimSigner (string fileName, string domain, string selector)
		{
			if (fileName == null)
				throw new ArgumentNullException ("fileName");

			if (fileName.Length == 0)
				throw new ArgumentException ("The file name cannot be empty.", "fileName");

			if (domain == null)
				throw new ArgumentNullException ("domain");

			if (selector == null)
				throw new ArgumentNullException ("selector");

			AsymmetricCipherKeyPair key;

			using (var stream = new StreamReader (fileName)) {
				var reader = new PemReader (stream);

				key = reader.ReadObject () as AsymmetricCipherKeyPair;
			}

			if (key == null)
				throw new FormatException ("Private key not found.");

			SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha256;
			PrivateKey = key.Private;
			Selector = selector;
			Domain = domain;
		}
Ejemplo n.º 34
0
 public Pkcs10CertificationRequest LoadCertificate(string pemFilenameCSR)
 {
     System.IO.StreamReader textReader = System.IO.File.OpenText(pemFilenameCSR);
     PemReader reader = new PemReader(textReader);
     return reader.ReadObject() as Pkcs10CertificationRequest;
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Load the cert/key pair from memory
        /// </summary>
        /// <returns>Value indicating success</returns>
        private bool LoadCertKeyPair()
        {
            var settings = ApplicationData.Current.RoamingSettings;
            if (settings.Values.ContainsKey("cert") && settings.Values.ContainsKey("key"))
            {
                string certStr = ApplicationData.Current.RoamingSettings.Values["cert"].ToString();
                string keyStr = ApplicationData.Current.RoamingSettings.Values["key"].ToString();

                PemReader certReader = new PemReader(new StringReader(certStr));
                PemReader keyReader = new PemReader(new StringReader(keyStr));

                keyPair = (AsymmetricCipherKeyPair)keyReader.ReadObject();
                cert = (X509Certificate)certReader.ReadObject();
                pemCertBytes = System.Text.Encoding.UTF8.GetBytes(certStr);

                return true;
            }
            // We didn't load the cert/key pair properly
            else
            {
                return false;
            }
        }
 private RsaKeyParameters GenerateKeysFromPem(byte[] rawData)
 {
   PemReader pem = new PemReader(new StreamReader(new MemoryStream( rawData )));
   RsaKeyParameters keyPair = (RsaKeyParameters)pem.ReadObject();
   return keyPair;
 }
 /// <summary>
 /// Retrieves the key pair from PEM format
 /// </summary>
 /// <param name="keyPairPemText">Key pair in pem format</param>
 /// <returns>Key pair</returns>
 public AsymmetricCipherKeyPair ImportKeyPair(string keyPairPemText)
 {
     using (var textReader = new StringReader(keyPairPemText))
     {
         var pemReader = new PemReader(textReader);
         var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
         return keyPair;
     }
 }
 /// <summary>
 /// Retrieves the certificate from Pem format.
 /// </summary>
 /// <param name="certificateText">Certificate in Pem format</param>
 /// <returns>An X509 certificate</returns>
 public X509Certificate ImportCertificate(string certificateText)
 {
     using (var textReader = new StringReader(certificateText))
     {
         var pemReader = new PemReader(textReader);
         var certificate = (X509Certificate)pemReader.ReadObject();
         return certificate;
     }
 }
Ejemplo n.º 39
-1
        private string EncryptDESKey()
        {
            var pemReader = new PemReader(_clientKeys.AbenityPublicKeyFileStream);
            var key = (AsymmetricKeyParameter)pemReader.ReadObject();

            var engine = new Pkcs1Encoding(new RsaEngine());
            engine.Init(true, key);

            var data = engine.ProcessBlock(_desKey, 0, _desKey.Length);

            return Utility.UrlEncode(Utility.Base64String(data)) + "decode";
        }