コード例 #1
0
        /// <inheritdoc />
        public async Task <IKey> ImportAsync(string name, string pem, char[] password = null, CancellationToken cancel = default(CancellationToken))
        {
            AsymmetricKeyParameter key;

            using (var sr = new StringReader(pem))
                using (var pf = new PasswordFinder {
                    Password = password
                })
                {
                    var reader = new PemReader(sr, pf);
                    try
                    {
                        key = reader.ReadObject() as AsymmetricKeyParameter;
                    }
                    catch (Exception e)
                    {
                        throw new UnauthorizedAccessException("The password is wrong.", e);
                    }
                    if (key == null || !key.IsPrivate)
                    {
                        throw new InvalidDataException("Not a valid PEM private key");
                    }
                }

            return(await AddPrivateKeyAsync(name, GetKeyPairFromPrivateKey(key), cancel));
        }
コード例 #2
0
ファイル: PemKeyFormatter.cs プロジェクト: dlech/SshAgentLib
        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);
              }
        }
コード例 #3
0
        public static void Problem5()
        {
            var finder = new PasswordFinder(new PasswordPrefixValidator("00000"),
                                            new ResumableIntSequenceGenerator());

            var password = finder.Find("ugkcyxxp", 8);

            Console.WriteLine("Password = {0}", password);
        }
コード例 #4
0
        public void FindViablePasswordShouldReturnGoodPasswords()
        {
            var pf        = new PasswordFinder(110033, 123444);
            var passwords = pf.FindViablePasswords().ToList();

            Assert.That(passwords, Has.Member(112233));
            Assert.That(passwords, Has.No.Member(123444));
            Assert.That(passwords, Does.Contain(111122));
        }
コード例 #5
0
        // == == == == == Puzzle 2 == == == == ==
        public static string Puzzle2(string input)
        {
            var inputs = input.Split("-");
            var low    = Convert.ToInt32(inputs[0]);
            var high   = Convert.ToInt32(inputs[1]);
            var pf     = new PasswordFinder(low, high, allowGroups: false);

            return(pf.FindNumberOfPasswords().ToString());
        }
コード例 #6
0
        public void Find_FindsCorrectNumber_ForSecretKey(string secretKey, string expected)
        {
            var sut = new PasswordFinder(new PasswordPrefixValidator("00000"),
                                         new ResumableIntSequenceGenerator(start: 3231929));

            var actual = sut.Find(secretKey, 8);

            Assert.Equal(expected, actual);
        }
コード例 #7
0
        private RSA GetKey(BoxConfig config)
        {
            var appAuth        = config.BoxSettings.AppAuth;
            var stringReader   = new StringReader(appAuth.PrivateKey);
            var passwordFinder = new PasswordFinder(appAuth.PassPhrase);
            var pemReader      = new PemReader(stringReader, passwordFinder);
            var keyParams      = (RsaPrivateCrtKeyParameters)pemReader.ReadObject();

            return(CreateRsaProvider(ToRsaParameters(keyParams)));
        }
コード例 #8
0
 void UseEncryptedKey(EncryptedKey key, Action <AsymmetricKeyParameter> action)
 {
     using (var sr = new StringReader(key.Pem))
         using (var pf = new PasswordFinder {
             Password = dek
         })
         {
             var reader     = new PemReader(sr, pf);
             var privateKey = (AsymmetricKeyParameter)reader.ReadObject();
             action(privateKey);
         }
 }
コード例 #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Day1 Star1");
            FuelRequirementsCalculator fuelRequirementsCalculator = new FuelRequirementsCalculator();

            Console.WriteLine($"Result: {fuelRequirementsCalculator.CalculateTotalFuelRequirements(InputReader.InputReader.ReadDay1Input())}");
            Console.WriteLine();

            Console.WriteLine("Day1 Star2");
            Day1.Star2.FuelRequirementsCalculator fuelRequirementsCalculator2 = new Day1.Star2.FuelRequirementsCalculator();
            Console.WriteLine($"Result: {fuelRequirementsCalculator2.CalculateTotalFuelRequirements(InputReader.InputReader.ReadDay1Input())}");
            Console.WriteLine();

            Console.WriteLine("Day 2 Star1");
            IntCodeComputer intCodeComputer = new IntCodeComputer();

            Console.WriteLine($"Result {intCodeComputer.Process(InputReader.InputReader.ReadDay2Input())}");
            Console.WriteLine();

            Console.WriteLine("Day 2 Star2");
            Day2.Star2.IntCodeComputer intCodeComputer2 = new Day2.Star2.IntCodeComputer();
            Console.WriteLine($"Result: {intCodeComputer2.FindInputsToProduceValue(InputReader.InputReader.ReadDay2Input(), 19690720)}");
            Console.WriteLine();

            Console.WriteLine("Day3 Star1");
            DistanceCalculator distanceCalculator = new DistanceCalculator();

            Console.WriteLine($"Result {distanceCalculator.CalculateDistance(InputReader.InputReader.ReadDay3Input())}");
            Console.WriteLine();

            Console.WriteLine("Day3 Star2");
            Day3.Star2.DistanceCalculator distanceCalculator2 = new Day3.Star2.DistanceCalculator();
            Console.WriteLine($"Result {distanceCalculator2.CalculateDistance(InputReader.InputReader.ReadDay3SmallInput())}");
            Console.WriteLine();

            Console.WriteLine("Day4 Star1");
            PasswordFinder passwordFinder = new PasswordFinder();

            Console.WriteLine($"Result: {passwordFinder.FindPossiblePasswords(145852, 616942).Count()}");
            Console.WriteLine();

            Console.WriteLine("Day4 Star2");
            Day4.Star2.PasswordFinder passwordFinder2 = new Day4.Star2.PasswordFinder();
            Console.WriteLine($"Result {passwordFinder2.FindPossiblePasswords(145852, 616942).Count()}");
        }
コード例 #10
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);
            }
        }
コード例 #11
0
        public override void Serialize(Stream aStream, object aObject)
        {
            /* check for required parameters */
            if (aStream == null)
            {
                throw new ArgumentNullException("aStream");
            }
            if (aObject == null)
            {
                throw new ArgumentNullException("aObject");
            }
            PasswordFinder pwFinder = null;

            if (GetPassphraseCallbackMethod != null)
            {
                pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
            }
            StreamWriter       streamWriter = new StreamWriter(aStream);
            PemWriter          writer       = new PemWriter(streamWriter);
            PinnedArray <char> passphrase   = null;

            if (pwFinder != null)
            {
                passphrase      = new PinnedArray <char>(0);
                passphrase.Data = pwFinder.GetPassword();
            }
            if (passphrase == null)
            {
                writer.WriteObject(aObject);
            }
            else
            {
                writer.WriteObject(aObject, null, passphrase.Data, null);
                passphrase.Dispose();
            }
        }
コード例 #12
0
        public override void Update(ViewModelReturnData VMReturnData)
        {
            if (VMReturnData.NewCardIssuer_Active)
            {
                this.View.Visibility = Visibility.Visible;

                #region Navigationbar details
                VMReturnData.ViewTitle = "New Issuer Card";
                VMReturnData.SubTitle  = "New Issuer details";
                //VMReturnData.CurrentPageNumber = 1;
                //VMReturnData.TotalPageNumber = 4;
                VMReturnData.MenuButtonEnabled = Visibility.Collapsed;
                VMReturnData.HelpButtonEnabled = Visibility.Visible;
                #endregion

                if (IssuerFileCardBtnPressed)
                {
                    IssuerFileCardBtnPressed = false;
                    MernokPasswordFile mernokPasswordFile = MernokPasswordManager.ReadMernokPasswordFile(V);
                    OpenFileDialog     openFileDialog1    = new OpenFileDialog();
                    openFileDialog1.Filter = "License Files|*.merlic";
                    openFileDialog1.Title  = "Select a Mernok Licnese File";
                    if (openFileDialog1.ShowDialog() == true)
                    {
                        // Assign the cursor in the Stream to the Form's Cursor property.
                        Console.WriteLine(Path.GetFullPath(openFileDialog1.FileName));
                        LicenseFilePath            = Path.GetFullPath(openFileDialog1.FileName);
                        CardDetailsFile            = CardDetailManager.ReadCardDetailFile(LicenseFilePath);
                        VMReturnData.VMCardDetails = CardDetailsFile.FCardDetails;
                        VMReturnData.NewCardUID    = CardDetailsFile.FCardDetails.cardUID;
                    }

                    //
                }

                if (CardDetailsFile.FCardDetails == null)
                {
                    WarningMessageF = "Please select a license file.";
                    CardUidPresVis  = Visibility.Collapsed;
                }
                else
                {
                    CardUidPresVis = Visibility.Visible;
                }

                if (!VMReturnData.CardInField)
                {
                    if (CardDetailsFile.FCardDetails != null)
                    {
                        WarningMessageI = "Present RFID card with UID: " + VMReturnData.cardInfoRead.UIDtoString(CardDetailsFile.FCardDetails.cardUID);
                    }
                    MessageColour = Brushes.OrangeRed;
                }
                else if (CardDetailsFile.FCardDetails != null && CardDetailsFile.FCardDetails.cardUID == VMReturnData.UID)
                {
                    VMReturnData.VMCardDetails.IssuerUID = CardinFieldUID = VMReturnData.UID;
                    MernokPasswordFile mernokPasswordFile = MernokPasswordManager.ReadMernokPasswordFile(V);
                    bool password = PasswordFinder.FindPasswordinFile(AdminPassword, mernokPasswordFile);
                    if (password)
                    {
                        PassColour = Brushes.GreenYellow;

                        string[] IssuerDetails = /*{ "1", "piet", "1", "2" };*/ PasswordDecriptor.PasswordToDetails(AdminPassword);
                        VMReturnData.VMCardDetails.EngineerName = IssuerDetails[3];
                        VMReturnData.VMCardDetails.EngineerUID  = UInt32.Parse(IssuerDetails[0]);
                        VMReturnData.NextButtonEnabled          = true;
                        WarningMessageI = "Password good, click next to continue";
                        MessageColour   = Brushes.White;
                    }
                    else
                    {
                        MessageColour = Brushes.OrangeRed;
                        PassColour    = Brushes.OrangeRed;
                        VMReturnData.NextButtonEnabled = false;
                        if (AdminPassword == "")
                        {
                            WarningMessageI = "Enter your password";
                        }
                        else
                        {
                            WarningMessageI = "Enter correct password";
                        }
                    }
                }
            }
            else
            {
                //View is not visible, do not update
                //Stop any animations on this vieModel
                this.View.Visibility = Visibility.Collapsed;
                AdminPassword        = "";
            }
        }
コード例 #13
0
ファイル: PemKeyFormatter.cs プロジェクト: dlech/SshAgentLib
 public override void Serialize(Stream aStream, object aObject)
 {
     /* check for required parameters */
       if (aStream == null) {
     throw new ArgumentNullException("aStream");
       }
       if (aObject == null) {
     throw new ArgumentNullException("aObject");
       }
       PasswordFinder pwFinder = null;
       if (GetPassphraseCallbackMethod != null) {
     pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
       }
       StreamWriter streamWriter = new StreamWriter(aStream);
       PemWriter writer = new PemWriter(streamWriter);
       PinnedArray<char> passphrase = null;
       if (pwFinder != null) {
     passphrase = new PinnedArray<char>(0);
     passphrase.Data = pwFinder.GetPassword();
       }
       if (passphrase == null) {
     writer.WriteObject(aObject);
       } else {
     writer.WriteObject(aObject, null, passphrase.Data, null);
     passphrase.Dispose();
       }
 }
コード例 #14
0
ファイル: Ssh1KeyFormatter.cs プロジェクト: dlech/SshAgentLib
        public override object Deserialize(Stream aStream)
        {
            /* check for required parameters */
              if (aStream == null) {
            throw new ArgumentNullException("aStream");
              }

              /* reading unencrypted part */
              BlobParser parser = new BlobParser(aStream);

              parser.ReadBytes((uint)FILE_HEADER_LINE.Length + 2);  //Skipping header line

              byte cipherType = parser.ReadByte();
              if (cipherType != SSH_CIPHER_3DES && cipherType != SSH_CIPHER_NONE) {
            //TripleDes is the only encryption supported
            throw new KeyFormatterException("Unsupported cypherType: " + cipherType);
              }

              parser.ReadInt(); //reserved

              /* reading public key */
              AsymmetricKeyParameter aPublicKeyParameter =
             parser.ReadSsh1PublicKeyData(false);
              String keyComment = parser.ReadString();

              /* reading private key */
              byte[] inputBuffer = new byte[aStream.Length];
              aStream.Read(inputBuffer, 0, inputBuffer.Length);
              byte[] ouputBuffer;

              try {
            if (cipherType == 3) {
              /* private key is 3DES encrypted */
              PasswordFinder pwFinder = null;
              if (GetPassphraseCallbackMethod != null) {
            pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
              }

              byte[] keydata;
              try {
            using (MD5 md5 = MD5.Create()) {
              char[] md5Buffer = pwFinder.GetPassword();
              keydata = md5.ComputeHash(Encoding.ASCII.GetBytes(md5Buffer));
            }
              } catch (PasswordException ex) {
            if (GetPassphraseCallbackMethod == null) {
              throw new CallbackNullException();
            }
            throw new KeyFormatterException("see inner exception", ex);
              }

              /* decryption */
              DesSsh1Engine desEngine = new DesSsh1Engine();
              desEngine.Init(false, new KeyParameter(keydata));

              BufferedBlockCipher bufferedBlockCipher = new BufferedBlockCipher(desEngine);
              ouputBuffer = bufferedBlockCipher.ProcessBytes(inputBuffer);

            } else {
              /* private key is stored in plain text */
              ouputBuffer = inputBuffer;
            }

            var privateKeyParser = new BlobParser(ouputBuffer);

            /* checking result of decryption */
            byte[] resultCheck = privateKeyParser.ReadBytes(4);
            if (resultCheck[0] != resultCheck[2] || resultCheck[1] != resultCheck[3]) {
              throw new KeyFormatterException("bad passphrase");
            }

            /* reading private key */
            var keyPair = privateKeyParser.ReadSsh1KeyData(aPublicKeyParameter);
            SshKey key = new SshKey(SshVersion.SSH1, keyPair);
            key.Comment = keyComment;
            return key;
              } catch (KeyFormatterException) {
            throw;
              } catch (Exception ex) {
            throw new KeyFormatterException("see inner exception", ex);
              }
        }
コード例 #15
0
        public override object Deserialize(Stream aStream)
        {
            /* check for required parameters */
            if (aStream == null)
            {
                throw new ArgumentNullException("aStream");
            }

            /* reading unencrypted part */
            BlobParser parser = new BlobParser(aStream);

            parser.ReadBytes((uint)FILE_HEADER_LINE.Length + 2); //Skipping header line

            byte cipherType = parser.ReadUInt8();

            if (cipherType != SSH_CIPHER_3DES && cipherType != SSH_CIPHER_NONE)
            {
                //TripleDes is the only encryption supported
                throw new KeyFormatterException("Unsupported cypherType: " + cipherType);
            }

            parser.ReadUInt32(); //reserved

            /* reading public key */
            AsymmetricKeyParameter aPublicKeyParameter =
                parser.ReadSsh1PublicKeyData(false);
            String keyComment = parser.ReadString();

            /* reading private key */
            byte[] inputBuffer = new byte[aStream.Length];
            aStream.Read(inputBuffer, 0, inputBuffer.Length);
            byte[] ouputBuffer;

            try {
                if (cipherType == 3)
                {
                    /* private key is 3DES encrypted */
                    PasswordFinder pwFinder = null;
                    if (GetPassphraseCallbackMethod != null)
                    {
                        pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
                    }

                    byte[] keydata;
                    try {
                        using (MD5 md5 = MD5.Create()) {
                            char[] md5Buffer = pwFinder.GetPassword();
                            keydata = md5.ComputeHash(Encoding.ASCII.GetBytes(md5Buffer));
                        }
                    } catch (PasswordException ex) {
                        if (GetPassphraseCallbackMethod == null)
                        {
                            throw new CallbackNullException();
                        }
                        throw new KeyFormatterException("see inner exception", ex);
                    }

                    /* decryption */
                    DesSsh1Engine desEngine = new DesSsh1Engine();
                    desEngine.Init(false, new KeyParameter(keydata));

                    BufferedBlockCipher bufferedBlockCipher = new BufferedBlockCipher(desEngine);
                    ouputBuffer = bufferedBlockCipher.ProcessBytes(inputBuffer);
                }
                else
                {
                    /* private key is stored in plain text */
                    ouputBuffer = inputBuffer;
                }

                var privateKeyParser = new BlobParser(ouputBuffer);

                /* checking result of decryption */
                byte[] resultCheck = privateKeyParser.ReadBytes(4);
                if (resultCheck[0] != resultCheck[2] || resultCheck[1] != resultCheck[3])
                {
                    throw new KeyFormatterException("bad passphrase");
                }

                /* reading private key */
                var    keyPair = privateKeyParser.ReadSsh1KeyData(aPublicKeyParameter);
                SshKey key     = new SshKey(SshVersion.SSH1, keyPair);
                key.Comment = keyComment;
                return(key);
            } catch (KeyFormatterException) {
                throw;
            } catch (Exception ex) {
                throw new KeyFormatterException("see inner exception", ex);
            }
        }
コード例 #16
0
ファイル: Ssh1KeyFormatter.cs プロジェクト: dlech/SshAgentLib
        public override void Serialize(Stream aStream, object aObject)
        {
            /* check for required parameters */
              if (aStream == null) {
            throw new ArgumentNullException("aStream");
              }

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

              PasswordFinder pwFinder = null;
              if (GetPassphraseCallbackMethod != null) {
            pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
              }
              PinnedArray<char> passphrase = null;
              if (pwFinder != null) {
            passphrase = new PinnedArray<char>(0);
            passphrase.Data = pwFinder.GetPassword();
              }

              byte cipherType;
              if (passphrase == null || passphrase.Data.Length == 0) {
            cipherType = SSH_CIPHER_NONE;
              } else {
            cipherType = SSH_CIPHER_3DES;
              }

              BlobBuilder builder = new BlobBuilder();

              ISshKey sshKey = aObject as ISshKey;
              RsaKeyParameters publicKeyParams = sshKey.GetPublicKeyParameters()
            as RsaKeyParameters;
              RsaPrivateCrtKeyParameters privateKeyParams = sshKey.GetPrivateKeyParameters()
            as RsaPrivateCrtKeyParameters;

              /* writing info headers */
              builder.AddBytes(Encoding.ASCII.GetBytes(FILE_HEADER_LINE + "\n"));
              builder.AddByte(0);          //end of string
              builder.AddByte(cipherType); //cipher
              builder.AddInt(0);           //reserved

              /* writing public key */
              builder.AddInt(sshKey.Size);
              builder.AddSsh1BigIntBlob(publicKeyParams.Modulus);
              builder.AddSsh1BigIntBlob(publicKeyParams.Exponent);
              builder.AddStringBlob(sshKey.Comment);

              /* writing private key */
              BlobBuilder privateKeyBuilder = new BlobBuilder();

              /* adding some control values */
              Random random = new Random();
              byte[] resultCheck = new byte[2];
              random.NextBytes(resultCheck);

              privateKeyBuilder.AddByte(resultCheck[0]);
              privateKeyBuilder.AddByte(resultCheck[1]);
              privateKeyBuilder.AddByte(resultCheck[0]);
              privateKeyBuilder.AddByte(resultCheck[1]);
              privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.Exponent);
              privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.DQ);
              privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.P);
              privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.Q);

              if (cipherType == SSH_CIPHER_NONE) {
            /* plain-text */
            builder.AddBytes(privateKeyBuilder.GetBlobAsPinnedByteArray().Data);
              } else {
            byte[] keydata;
            using (MD5 md5 = MD5.Create()) {
              keydata = md5.ComputeHash(Encoding.ASCII.GetBytes(passphrase.Data));
            }

            /* encryption */
            DesSsh1Engine desEngine = new DesSsh1Engine();
            desEngine.Init(true, new KeyParameter(keydata));

            BufferedBlockCipher bufferedBlockCipher = new BufferedBlockCipher(desEngine);
            byte[] ouputBuffer = bufferedBlockCipher.ProcessBytes(
              privateKeyBuilder.GetBlobAsPinnedByteArray().Data);

            builder.AddBytes(ouputBuffer);

            passphrase.Dispose();
              }

              /* writing result to file */
              var builderOutput = builder.GetBlobAsPinnedByteArray();
              aStream.Write(builderOutput.Data, 0, builderOutput.Data.Length);
              aStream.Close();
        }
コード例 #17
0
 public void ValidRange()
 {
     int start  = 264793;
     int end    = 803935;
     var result = PasswordFinder.CheckRange(start, end);
 }
コード例 #18
0
        [TestCase(111122, true)]  // repeating group
        public void Validate(int input, bool isValid)
        {
            var result = PasswordFinder.IsValid(input);

            Assert.AreEqual(isValid, result);
        }
コード例 #19
0
        public override void Serialize(Stream aStream, object aObject)
        {
            /* check for required parameters */
            if (aStream == null)
            {
                throw new ArgumentNullException("aStream");
            }

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

            PasswordFinder pwFinder = null;

            if (GetPassphraseCallbackMethod != null)
            {
                pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
            }
            PinnedArray <char> passphrase = null;

            if (pwFinder != null)
            {
                passphrase      = new PinnedArray <char>(0);
                passphrase.Data = pwFinder.GetPassword();
            }

            byte cipherType;

            if (passphrase == null || passphrase.Data.Length == 0)
            {
                cipherType = SSH_CIPHER_NONE;
            }
            else
            {
                cipherType = SSH_CIPHER_3DES;
            }

            BlobBuilder builder = new BlobBuilder();

            ISshKey          sshKey          = aObject as ISshKey;
            RsaKeyParameters publicKeyParams = sshKey.GetPublicKeyParameters()
                                               as RsaKeyParameters;
            RsaPrivateCrtKeyParameters privateKeyParams = sshKey.GetPrivateKeyParameters()
                                                          as RsaPrivateCrtKeyParameters;

            /* writing info headers */
            builder.AddBytes(Encoding.ASCII.GetBytes(FILE_HEADER_LINE + "\n"));
            builder.AddUInt8(0);          //end of string
            builder.AddUInt8(cipherType); //cipher
            builder.AddInt(0);            //reserved

            /* writing public key */
            builder.AddInt(sshKey.Size);
            builder.AddSsh1BigIntBlob(publicKeyParams.Modulus);
            builder.AddSsh1BigIntBlob(publicKeyParams.Exponent);
            builder.AddStringBlob(sshKey.Comment);

            /* writing private key */
            BlobBuilder privateKeyBuilder = new BlobBuilder();

            /* adding some control values */
            Random random = new Random();

            byte[] resultCheck = new byte[2];
            random.NextBytes(resultCheck);

            privateKeyBuilder.AddUInt8(resultCheck[0]);
            privateKeyBuilder.AddUInt8(resultCheck[1]);
            privateKeyBuilder.AddUInt8(resultCheck[0]);
            privateKeyBuilder.AddUInt8(resultCheck[1]);
            privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.Exponent);
            privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.DQ);
            privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.P);
            privateKeyBuilder.AddSsh1BigIntBlob(privateKeyParams.Q);

            if (cipherType == SSH_CIPHER_NONE)
            {
                /* plain-text */
                builder.AddBytes(privateKeyBuilder.GetBlobAsPinnedByteArray().Data);
            }
            else
            {
                byte[] keydata;
                using (MD5 md5 = MD5.Create()) {
                    keydata = md5.ComputeHash(Encoding.ASCII.GetBytes(passphrase.Data));
                }

                /* encryption */
                DesSsh1Engine desEngine = new DesSsh1Engine();
                desEngine.Init(true, new KeyParameter(keydata));

                BufferedBlockCipher bufferedBlockCipher = new BufferedBlockCipher(desEngine);
                byte[] ouputBuffer = bufferedBlockCipher.ProcessBytes(
                    privateKeyBuilder.GetBlobAsPinnedByteArray().Data);

                builder.AddBytes(ouputBuffer);

                passphrase.Dispose();
            }

            /* writing result to file */
            var builderOutput = builder.GetBlobAsPinnedByteArray();

            aStream.Write(builderOutput.Data, 0, builderOutput.Data.Length);
            aStream.Close();
        }
コード例 #20
0
        /// <summary>
        /// Generates a JwtToken to use for login.
        /// </summary>
        /// <returns>The generated JWT token.</returns>
        private string GenerateJwtToken()
        {
            logger.Info("Key-pair Authentication");

            bool hasPkPath =
                session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY_FILE, out var pkPath);
            bool hasPkContent =
                session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY, out var pkContent);

            session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY_PWD, out var pkPwd);

            // Extract the public key from the private key to generate the fingerprints
            RSAParameters           rsaParams;
            String                  publicKeyFingerPrint = null;
            AsymmetricCipherKeyPair keypair = null;

            using (TextReader tr =
                       hasPkPath ? (TextReader) new StreamReader(pkPath) : new StringReader(pkContent))
            {
                try
                {
                    PemReader pr = null;
                    if (null != pkPwd)
                    {
                        IPasswordFinder ipwdf = new PasswordFinder(pkPwd);
                        pr = new PemReader(tr, ipwdf);
                    }
                    else
                    {
                        pr = new PemReader(tr);
                    }

                    object key = pr.ReadObject();
                    // Infer what the pem reader is sending back based on the object properties
                    if (key.GetType().GetProperty("Private") != null)
                    {
                        // PKCS1 key
                        keypair   = (AsymmetricCipherKeyPair)key;
                        rsaParams = DotNetUtilities.ToRSAParameters(
                            keypair.Private as RsaPrivateCrtKeyParameters);
                    }
                    else
                    {
                        // PKCS8 key
                        RsaPrivateCrtKeyParameters pk = (RsaPrivateCrtKeyParameters)key;
                        rsaParams = DotNetUtilities.ToRSAParameters(pk);
                        keypair   = DotNetUtilities.GetRsaKeyPair(rsaParams);
                    }
                    if (keypair == null)
                    {
                        throw new Exception("Unknown error.");
                    }
                }
                catch (Exception e)
                {
                    throw new SnowflakeDbException(
                              SFError.JWT_ERROR_READING_PK,
                              hasPkPath ? pkPath : "with value passed in connection string",
                              e.ToString(),
                              e);
                }
            }

            // Generate the public key fingerprint
            var publicKey = keypair.Public;

            byte[] publicKeyEncoded =
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded();
            using (SHA256 SHA256Encoder = SHA256.Create())
            {
                byte[] sha256Hash = SHA256Encoder.ComputeHash(publicKeyEncoded);
                publicKeyFingerPrint = "SHA256:" + Convert.ToBase64String(sha256Hash);
            }

            // Generating the token
            var now = DateTime.UtcNow;

            System.DateTime dtDateTime =
                new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            long secondsSinceEpoch = (long)((now - dtDateTime).TotalSeconds);

            /*
             * Payload content
             *      iss : $accountName.$userName.$pulicKeyFingerprint
             *      sub : $accountName.$userName
             *      iat : $now
             *      exp : $now + LIFETIME
             *
             * Note : Lifetime = 120sec for Python impl, 60sec for Jdbc and Odbc
             */
            String accountUser =
                session.properties[SFSessionProperty.ACCOUNT].ToUpper() +
                "." +
                session.properties[SFSessionProperty.USER].ToUpper();
            String issuer = accountUser + "." + publicKeyFingerPrint;
            var    claims = new[] {
                new Claim(
                    JwtRegisteredClaimNames.Iat,
                    secondsSinceEpoch.ToString(),
                    System.Security.Claims.ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Sub, accountUser),
            };

            rsaProvider.ImportParameters(rsaParams);
            var token = new JwtSecurityToken(
                // Issuer
                issuer,
                // Audience
                null,
                // Subject
                claims,
                //NotBefore
                null,
                // Expires
                now.AddSeconds(60),
                //SigningCredentials
                new SigningCredentials(
                    new RsaSecurityKey(rsaProvider), SecurityAlgorithms.RsaSha256)
                );

            // Serialize the jwt token
            // Base64URL-encoded parts delimited by period ('.'), with format :
            //     [header-base64url].[payload-base64url].[signature-base64url]
            var    handler  = new JwtSecurityTokenHandler();
            string jwtToken = handler.WriteToken(token);

            return(jwtToken);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: RSA-PM/RSA-PM
 public static bool LoadPemFile(string fn, out RSAParameters load_pem_rsa)
 {
     load_pem_rsa = new RSAParameters();
     bool tryWithPass = false;
     while (true)
     {
         PasswordFinder pempass = null;
         if (tryWithPass)
         {
             var szpempass = InputBox("What is the PEM Passphrase", null, true);
             if (szpempass == null)
             {
                 return false;
             }
             pempass = new PasswordFinder(szpempass.ToCharArray());
         }
         try
         {
             if (Shared.LoadKey(fn, pempass, out load_pem_rsa) == false)
             {
                 MessageBox.Show("This does not have a private key. Select a different file");
                 return false;
             }
             break;
         }
         catch (CryptographicException ex)
         {
             MessageBox.Show("I don't like this pem file. Try a different one");
             return false;
         }
         catch (Org.BouncyCastle.Security.PasswordException ex)
         {
             tryWithPass = true;
             continue;
         }
         catch (Org.BouncyCastle.Crypto.InvalidCipherTextException ex)
         {
             //if (ex.Message.IndexOf(@"how to load this as a key") != -1)
             {
                 MessageBox.Show("Incorrect Passphrase");
                 continue;
             }
             throw;
         }
     }
     return true;
 }