InstagramApiSharp icon indicating copy to clipboard operation
InstagramApiSharp copied to clipboard

Encrypted password ( enc_password )

Open ramtinak opened this issue 4 years ago • 0 comments

Hi, For anyone who is looking for C# version of enc_password: It's for .NET Standard 2.0 and newer (.NET Framework 4.6.1 and newer)

// Copyright (c) 2020 - Ramtin Jokar [ [email protected] ]
        public static string GetEncryptedPassword(this IInstaApi api, string password) 
        {
            SecureRandom secureRandom = new SecureRandom();
            var pubKey = api.GetLoggedUser().PublicKey;
            var pubKeyId = api.GetLoggedUser().PublicKeyId;
            byte[] randKey = new byte[32];
            byte[] iv = new byte[12];
            secureRandom.NextBytes(randKey, 0, randKey.Length);
            secureRandom.NextBytes(iv, 0, iv.Length);
            long time = DateTime.UtcNow.ToUnixTime();
            byte[] associatedData = Encoding.UTF8.GetBytes(time.ToString());
            var pubKEY = Encoding.UTF8.GetString(Convert.FromBase64String(pubKey));
            byte[] encryptedKey;
            using (var rdr = PemKeyUtils.GetRSAProviderFromPemString(pubKEY.Trim()))
                encryptedKey = rdr.Encrypt(randKey, false);

            byte[] plaintext = Encoding.UTF8.GetBytes(password);

            var cipher = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(new KeyParameter(randKey), 128, iv, associatedData);
            cipher.Init(true, parameters);

            var ciphertext = new byte[cipher.GetOutputSize(plaintext.Length)];
            var len = cipher.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0);
            cipher.DoFinal(ciphertext, len);

            var con = new byte[plaintext.Length];
            Buffer.BlockCopy(ciphertext, 0, con, 0, plaintext.Length);
            ciphertext = con;
            var tag = cipher.GetMac();

            byte[] buffersSize = BitConverter.GetBytes(Convert.ToInt16(encryptedKey.Length));

            byte[] encKeyIdBytes = BitConverter.GetBytes(Convert.ToUInt16(pubKeyId));
            if (BitConverter.IsLittleEndian)
                Array.Reverse(encKeyIdBytes);
            encKeyIdBytes[0] = 1; 
            var payload = Convert.ToBase64String(encKeyIdBytes.Concat(iv).Concat(buffersSize).Concat(encryptedKey).Concat(tag).Concat(ciphertext).ToArray());

            return $"#PWD_INSTAGRAM:4:{time}:{payload}";
        }

BouncyCastle package is required.

If you have any problem with it, search in Google! It's a built-in feature in Private Repo (Paid version).

Have a great day.

ramtinak avatar Aug 31 '20 13:08 ramtinak