Instagram-private-api: How can I generate enc_password?

Created on 9 Dec 2019  ·  143Comments  ·  Source: dilame/instagram-private-api

Question

Hello people, I got a new header value. I just wanna ask, have you ever see that and do you know how can I generate it?
That's my value.
"enc_password":"#PWD_INSTAGRAM:4:1575910572:Ac09XDpcBE1cB/lOovUAAUfoGhWI59ZQtRLVbpku9bHOJAUNZOszYmzbaV7bWVwrc/AgVoPvn4Sm68625fI4S9CUyqR7PYkSvaXdsD98JmhQFBRjntw/2eR93Wqxzq05AGmcdiXcNaboW2ltmkWFoUL8fZnfbNtoXVVVZ6n7aYFplud2UJ+A/zYFVsTSsoGbvdBIyjttMKcNQNsotAo95pA+v99q39PRZ0ug3B7GrfOayV+t7OTointqxZjoxYtjmqda4n7kBsruEVW7yBfnAU0k9pWScVtjJXEkoGejJtDbd5RUBUPJVJIlVDjCgLZ2hmKYOYO16C5nvFNx3jkc4AwujIZOl6mqlhKs+Xehmr33Nk7euoe8Lj3XPDH1HpiYuSxBI1Lp1Rm8JzM="

discussion question

Most helpful comment

A gift for you people:

    public static function encryptPassword(
        $password,
        $publicKeyId,
        $publicKey)
    {
        $key = openssl_random_pseudo_bytes(32);
        $iv = openssl_random_pseudo_bytes(12);
        $time = time();

        openssl_public_encrypt($key ,$encryptedAesKey, base64_decode($publicKey));
        $encrypted = openssl_encrypt($password, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, strval($time));

        $payload = base64_encode("\x01" | pack('n', intval($publicKeyId)) . $iv . pack('s', strlen($encryptedAesKey)) . $encryptedAesKey . $tag . $encrypted);

        return sprintf('#PWD_INSTAGRAM:4:%s:%s', $time, $payload);
    }

IG Android default public key (ID: 41):

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvcu1KMDR1vzuBr9iYKW8
KWmhT8CVUBRkchiO8861H7zIOYRwkQrkeHA+0mkBo3Ly1PiLXDkbKQZyeqZbspke
4e7WgFNwT23jHfRMV/cNPxjPEy4kxNEbzLET6GlWepGdXFhzHfnS1PinGQzj0ZOU
ZM3pQjgGRL9fAf8brt1ewhQ5XtpvKFdPyQq5BkeFEDKoInDsC/yKDWRAx2twgPFr
CYUzAB8/yXuL30ErTHT79bt3yTnv1fRtE19tROIlBuqruwSBk9gGq/LuvSECgsl5
z4VcpHXhgZt6MhrAj6y9vAAxO2RVrt0Mq4OY4HgyYz9Wlr1vAxXXGAAYIvrhAYLP
7QIDAQAB
-----END PUBLIC KEY-----

Public Key returned on API responses (ID: 205):

const IG_LOGIN_ANDROID_PUBLIC_KEY= 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF1enRZOEZvUlRGRU9mK1RkTGlUdAplN3FIQXY1cmdBMmk5RkQ0YjgzZk1GK3hheW14b0xSdU5KTitRanJ3dnBuSm1LQ0QxNGd3K2w3TGQ0RHkvRHVFCkRiZlpKcmRRWkJIT3drS3RqdDdkNWlhZFdOSjdLczlBM0NNbzB5UktyZFBGU1dsS21lQVJsTlFrVXF0YkNmTzcKT2phY3ZYV2dJcGlqTkdJRVk4UkdzRWJWZmdxSmsrZzhuQWZiT0xjNmEwbTMxckJWZUJ6Z0hkYWExeFNKOGJHcQplbG4zbWh4WDU2cmpTOG5LZGk4MzRZSlNaV3VxUHZmWWUrbEV6Nk5laU1FMEo3dE80eWxmeWlPQ05ycnF3SnJnCjBXWTFEeDd4MHlZajdrN1NkUWVLVUVaZ3FjNUFuVitjNUQ2SjJTSTlGMnNoZWxGNWVvZjJOYkl2TmFNakpSRDgKb1FJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==';

Format:

Sample (Hex representation):

01 **(ID: 0x01)**
cd **(Pub. ID: 205)**
3d5c3a5c044d5c07f94ea2f5 **(IV)**
0001 **(256 RSA length little endian)**
47e81a1588e7d650b512d56e992ef5b1ce24050d64eb33626cdb695edb595c2b73f0205683ef9f84a6ebceb6e5f2384bd094caa47b3d8912bda5ddb03f7c2668501414639edc3fd9e47ddd6ab1cead3900699c7625dc35a6e85b696d9a4585a142fc7d99df6cdb685d555567a9fb69816996e776509f80ff360556c4d2b2819bbdd048ca3b6d30a70d40db28b40a3de6903ebfdf6adfd3d1674ba0dc1ec6adf39ac95fadece4e88a7b6ac598e8c58b639aa75ae27ee406caee1155bbc817e7014d24f69592715b63257124a067a326d0db7794540543c95492255438c280b6768662983983b5e82e67bc5371de391ce00c2e8c864e97a9aa9612acf977a19abd **RSA Enc. Key**
f7364edeba87bc2e3dd73c31f51e9898 **AES GCM TAG**
b92c412352e9d519bc2733 **Enc. PW**

Happy new year! 🎉

All 143 comments

Ok, I found somethings.. I want to share, maybe we can find the solution together;

I believe this is rc-40 crypto.. Not sure but it looks like rc-40.
Anyway, I have public key but I couldn't decrypt it..
public key returns on header;
LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF1enRZOEZvUlRGRU9mK1RkTGlUdAplN3FIQXY1cmdBMmk5RkQ0YjgzZk1GK3hheW14b0xSdU5KTitRanJ3dnBuSm1LQ0QxNGd3K2w3TGQ0RHkvRHVFCkRiZlpKcmRRWkJIT3drS3RqdDdkNWlhZFdOSjdLczlBM0NNbzB5UktyZFBGU1dsS21lQVJsTlFrVXF0YkNmTzcKT2phY3ZYV2dJcGlqTkdJRVk4UkdzRWJWZmdxSmsrZzhuQWZiT0xjNmEwbTMxckJWZUJ6Z0hkYWExeFNKOGJHcQplbG4zbWh4WDU2cmpTOG5LZGk4MzRZSlNaV3VxUHZmWWUrbEV6Nk5laU1FMEo3dE80eWxmeWlPQ05ycnF3SnJnCjBXWTFEeDd4MHlZajdrN1NkUWVLVUVaZ3FjNUFuVitjNUQ2SjJTSTlGMnNoZWxGNWVvZjJOYkl2TmFNakpSRDgKb1FJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==

It's evp_aes_256_gcm encrypted.

thank you very much, I am investigating it now... I never hear it before 👍

Hey guys, did you found the solution what need to do with it?


Here is some very rough code to generate the enc_password (expand)

const WebCrypto = require("node-webcrypto-ossl");
const webcrypto = new WebCrypto()
const tweetnacl = require("tweetnacl")
tweetnacl.sealedbox = require('tweetnacl-sealedbox-js');
const fetch = require('node-fetch');

data = {
    key_id: "",
    public_key: "",
    password: "",
    time: Date.now(),
    timeEncoded: "",
    password_length: 0
}

encryptPassword("password")

async function encryptPassword(password) {
    password_length = password.length
    data.password = password
    data.password = decodeUTF8(data.password)
    data.timeEncoded = decodeUTF8(data.time)


    var options = {
        method: 'GET',
        headers: {
            //'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'accept-langauge': 'en-US;q=0.9,en;q=0.8,es;q=0.7',
            'origin': 'https://www.instagram.com',
            'referer': 'https://www.instagram.com/',
            'upgrade-insecure-requests': '1',
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'x-requested-with': 'XMLHttpRequest',
        }
    }

    let res = await fetch('https://www.instagram.com/data/shared_data/', options)
    res = await res.json()
    data.key_id = res.encryption.key_id
    data.public_key = res.encryption.public_key
    console.log(data)
    let key = await encrypt(data.key_id, data.public_key, data.password, data.timeEncoded)
    key = encodeURIComponent(key)
    return key
}



async function encrypt(key, pkey, password, time) {

    const pLength = 100 + password.length

    if (64 !== pkey.length) {
        throw new Error("Public key is not valid hex string")
    }

    pkey = parsePkey(pkey)

    if (!pkey) {
        throw new Error("Public key is not valid hex string")
    }

    let y = new Uint8Array(pLength);

    let f = 0;
    y[f] = 1
    y[f += 1] = key
    f += 1

    let p = {
        name: 'AES-GCM',
        iv: new Uint8Array(12),
        additionalData: time,
        tagLen: password_length
    }

    const CryptoKey = await webcrypto.subtle.generateKey({
        name: 'AES-GCM',
        length: 256
    }, !0, ['encrypt', 'decrypt'])

    const ckey = await webcrypto.subtle.exportKey('raw', CryptoKey)

    let ciphertext = await webcrypto.subtle.encrypt(p, CryptoKey, password.buffer)

    let sealed = tweetnacl.sealedbox.seal(new Uint8Array(ckey), pkey)


    if (y[f] = 255 & sealed.length,
        y[f + 1] = sealed.length >> 8 & 255,
        f += 2,
        y.set(sealed, f),
        f += 32,
        f += 48,
        sealed.length !== 32 + 48) {}

    const s = new Uint8Array(ciphertext)
    const c = s.slice(-password_length)
    const h = s.slice(0, password_length)
    y.set(c, f)
    f += 16,
        y.set(h, f),
        y

    let app= 6
    let t = ["#PWD_INSTAGRAM_BROWSER", app, data.time, btoa(y)].join(':')
    console.log(t)

}


function parsePkey(pkey) {
    const n = []
    for (let o = 0; o < pkey.length; o += 2)
        n.push(parseInt(pkey.slice(o, o + 2), 16));
    return new Uint8Array(n)
}

function decodeUTF8(n) {
    n = unescape(encodeURIComponent(n))
    let c = new Uint8Array(n.length)

    for (t = 0; t < n.length; t++)
        c[t] = n.charCodeAt(t);
    return c

}



//https://www.instagram.com/data/shared_data/'

//https://www.instagram.com/static/bundles/es6/EncryptionUtils.js/c808b8dee83e.js:formatted
//line 23-24
//      const n = '#PWD_INSTAGRAM_BROWSER'
//      , c = 6;

This is for the web-version. But it's similar. But your enc-version is here 6, in the app, it's 4.

@Nerixyz how much similar? Is only differences about version?

They both encrypt the aes-key with rsa and put it into a buffer. ~I can paste my current code here later.~

This is my take. It doesn't work, bu I know the keyId is at least right. This is then sent to enc_password: `#PWD_INSTAGRAM:4:${time}:${encrypted}`,

function encryptPassword(password: string): { time: string, encrypted: string } {
  const plainKey = Buffer.from(ig.state.passwordEncryptionPubKey, 'base64').toString();
  const randKey = crypto.randomBytes(32);
  const iv = crypto.randomBytes(12);
  const resEncrypted = crypto.publicEncrypt(plainKey, randKey);
  const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
  const time = Math.floor(Date.now() / 1000).toString();
  cipher.setAAD(Buffer.from(time));
  const aesEncrypted = concat(cipher.update(password, 'utf8'), cipher.final());
  const sizeBuffer = Buffer.alloc(2, 0);
  sizeBuffer.writeInt16LE(resEncrypted.byteLength, 0);
  const authTag = cipher.getAuthTag();
  return {
    time,
    encrypted: concat(
      Buffer.from([1, ig.state.passwordEncryptionKeyId]),
      iv,
      sizeBuffer,
      resEncrypted, aesEncrypted, authTag)
      .toString('base64'),
  };
}

@Nerixyz thank you for your response, it's very explanatory... I try to solve, I hope we can...

I'm also stuck on it, did anyone find a way to generate the enc_password ?

not me unfortunately.. that beats me

password: adminka55
enc_password: #PWD_INSTAGRAM_BROWSER:6:1573829509755:encodeBase64(encrypt("AES-GCM-256","adminka55","1573829509755"))

is that working? @Frake7 but this is web right? and there is no pub_key?

This is my take. It doesn't work, bu I know the keyId is at least right. This is then sent to enc_password: `#PWD_INSTAGRAM:4:${time}:${encrypted}`,

function encryptPassword(password: string): { time: string, encrypted: string } {
  const plainKey = Buffer.from(ig.state.passwordEncryptionPubKey, 'base64').toString();
  const randKey = crypto.randomBytes(32);
  const iv = crypto.randomBytes(12);
  const resEncrypted = crypto.publicEncrypt(plainKey, randKey);
  const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
  const time = Math.floor(Date.now() / 1000).toString();
  cipher.setAAD(Buffer.from(time));
  const aesEncrypted = concat(cipher.update(password, 'utf8'), cipher.final());
  const sizeBuffer = Buffer.alloc(2, 0);
  sizeBuffer.writeInt16LE(resEncrypted.byteLength, 0);
  const authTag = cipher.getAuthTag();
  return {
    time,
    encrypted: concat(
      Buffer.from([1, ig.state.passwordEncryptionKeyId]),
      iv,
      sizeBuffer,
      resEncrypted, aesEncrypted, authTag)
      .toString('base64'),
  };
}

I use this for now.... I made some changes for node.js, I don't know why you said it is not working. If you can explain I can try to fix it.

It's able to encrypt but the request fails.

It works on me, I only changed some small things for node.js.
Thank you very much by the way @Nerixyz I am very happy about it.

It works on me, I only changed some small things for node.js.
Thank you very much by the way @Nerixyz I am very happy about it.

Could you paste your code here? I've also used node for this.

@Nerixyz here you are

const crypto = require('crypto');

const getEncPassword = (password, pubKey, keyID) => {
    const plainKey = Buffer.from(pubKey, 'base64').toString();
    const randKey = crypto.randomBytes(32);
    const iv = crypto.randomBytes(12);
    const resEncrypted = crypto.publicEncrypt(plainKey, randKey);
    const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
    const time = Math.floor(Date.now() / 1000).toString();
    cipher.setAAD(Buffer.from(time));
    const aesEncrypted = Buffer.concat([cipher.update(password, 'utf8'), cipher.final()]);
    const sizeBuffer = Buffer.alloc(2, 0);
    sizeBuffer.writeInt16LE(resEncrypted.byteLength, 0);
    const authTag = cipher.getAuthTag();
    const pass = Buffer.concat(
        [Buffer.from([1, keyID]),
        iv,
        sizeBuffer,
        resEncrypted, aesEncrypted, authTag])
        .toString('base64')
    console.log(`#PWD_INSTAGRAM:4:${time}:${pass}`)
}

@Nerixyz @ozican why do you think that working correctly? If we capture requests and set up values like there (I mean time, keys) - enc_password must be the same. But it's not the same

@Keln54 It will never be. As you can see, a RANDOM key is created that is then encrypted with the pkey.

@Nerixyz so, why do you think they must be random? Where you get this information?) I think not, because - how do instagram check the correct of this value? They must take time and pass - then check enc_password sending by your side with enc_password they get.

Typically then messages are not encrypted directly with such keys but are instead encrypted using a symmetric "session" key. This key is itself then encrypted using the public key.

https://wiki.openssl.org/index.php/EVP_Asymmetric_Encryption_and_Decryption_of_an_Envelope

sorry for my low knowledge, what do you think? @Nerixyz is everything ok now? I mean, is that encrypt method is right?

Because I think, if you put same values, crypted data can be different with this crypto method. am I right or not?

The aes-gcm is right and also the public-key encryption is right. Only the order of concatenation and maybe some small settings are wrong.

OK great because I think I can investigate more about it.

@Nerixyz here you are

const crypto = require('crypto');

const getEncPassword = (password, pubKey, keyID) => {
    const plainKey = Buffer.from(pubKey, 'base64').toString();
    const randKey = crypto.randomBytes(32);
    const iv = crypto.randomBytes(12);
    const resEncrypted = crypto.publicEncrypt(plainKey, randKey);
    const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
    const time = Math.floor(Date.now() / 1000).toString();
    cipher.setAAD(Buffer.from(time));
    const aesEncrypted = Buffer.concat([cipher.update(password, 'utf8'), cipher.final()]);
    const sizeBuffer = Buffer.alloc(2, 0);
    sizeBuffer.writeInt16LE(resEncrypted.byteLength, 0);
    const authTag = cipher.getAuthTag();
    const pass = Buffer.concat(
        [Buffer.from([1, keyID]),
        iv,
        sizeBuffer,
        resEncrypted, aesEncrypted, authTag])
        .toString('base64')
    console.log(`#PWD_INSTAGRAM:4:${time}:${pass}`)
}

does this work for you?

I have an error with "const resEncrypted = crypto.publicEncrypt(plainKey, randKey);" - error:0906D06C:PEM routines:PEM_read_bio:no start line

I have an error with "const resEncrypted = crypto.publicEncrypt(plainKey, randKey);" - error:0906D06C:PEM routines:PEM_read_bio:no start line

Is your public key from ig.state.passwordEncryptionPubKey?

does this work for you?

This works. But the request using this password fails with "Oops, an error occurred.".

does this work for you?

This works. But the request using this password fails with "Oops, an error occurred.".

same thing =( Is there any solution?

does this work for you?

This works. But the request using this password fails with "Oops, an error occurred.".

strange because I don't get that error. I successfully login or create

@ozican How so you log in then?

@Nerixyz I might have the solution or most of it. Ping me if you want to share ideas (email on profile)

Regards

@crouchingtiger Hello. Yes I get my keyID and pubKey from header. I am not on my main computer now but it is like; ig-set-keyIdand ìg-set-pubKey`
by the way for some test I can give to you a rest API for test it (only for @Nerixyz and @crouchingtiger and @mgp25 ) (because of server is not enough powerfull)
just email me if you want.. [email protected]

I have solved it already, I am not with the computer but if you send me a hex dump via email I can guide you for the implementation

regards

Don't RSA encrypt the public key as shown in the node.js code above.

The public key isn't encrypted. The key used for the AES-GCM encryption is encrypted here. This is in fact the result you get in the ek buffer.

The "updated" code loks like this:

const randKey = crypto.randomBytes(32);
  const iv = crypto.randomBytes(12);
  const rsaEncrypted = crypto.publicEncrypt(Buffer.from(ig.state.passwordEncryptionPubKey, 'base64').toString(), randKey);
  const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
  const time = Math.floor(Date.now() / 1000).toString();
  const aesEncrypted = concat(cipher.setAAD(Buffer.from(time)).update(password), cipher.final());
  const authTag = cipher.getAuthTag();
  const sizeBuffer = Buffer.alloc(2, 0);
  sizeBuffer.writeInt16LE(rsaEncrypted.byteLength, 0);
  return {
    time,
    encrypted: concat(
      Buffer.from([1, ig.state.passwordEncryptionKeyId]),
      iv,
      sizeBuffer,
      rsaEncrypted,
      authTag,
      aesEncrypted)
      .toString('base64'),
  };

There's still something wrong.

A gift for you people:

    public static function encryptPassword(
        $password,
        $publicKeyId,
        $publicKey)
    {
        $key = openssl_random_pseudo_bytes(32);
        $iv = openssl_random_pseudo_bytes(12);
        $time = time();

        openssl_public_encrypt($key ,$encryptedAesKey, base64_decode($publicKey));
        $encrypted = openssl_encrypt($password, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, strval($time));

        $payload = base64_encode("\x01" | pack('n', intval($publicKeyId)) . $iv . pack('s', strlen($encryptedAesKey)) . $encryptedAesKey . $tag . $encrypted);

        return sprintf('#PWD_INSTAGRAM:4:%s:%s', $time, $payload);
    }

IG Android default public key (ID: 41):

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvcu1KMDR1vzuBr9iYKW8
KWmhT8CVUBRkchiO8861H7zIOYRwkQrkeHA+0mkBo3Ly1PiLXDkbKQZyeqZbspke
4e7WgFNwT23jHfRMV/cNPxjPEy4kxNEbzLET6GlWepGdXFhzHfnS1PinGQzj0ZOU
ZM3pQjgGRL9fAf8brt1ewhQ5XtpvKFdPyQq5BkeFEDKoInDsC/yKDWRAx2twgPFr
CYUzAB8/yXuL30ErTHT79bt3yTnv1fRtE19tROIlBuqruwSBk9gGq/LuvSECgsl5
z4VcpHXhgZt6MhrAj6y9vAAxO2RVrt0Mq4OY4HgyYz9Wlr1vAxXXGAAYIvrhAYLP
7QIDAQAB
-----END PUBLIC KEY-----

Public Key returned on API responses (ID: 205):

const IG_LOGIN_ANDROID_PUBLIC_KEY= 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF1enRZOEZvUlRGRU9mK1RkTGlUdAplN3FIQXY1cmdBMmk5RkQ0YjgzZk1GK3hheW14b0xSdU5KTitRanJ3dnBuSm1LQ0QxNGd3K2w3TGQ0RHkvRHVFCkRiZlpKcmRRWkJIT3drS3RqdDdkNWlhZFdOSjdLczlBM0NNbzB5UktyZFBGU1dsS21lQVJsTlFrVXF0YkNmTzcKT2phY3ZYV2dJcGlqTkdJRVk4UkdzRWJWZmdxSmsrZzhuQWZiT0xjNmEwbTMxckJWZUJ6Z0hkYWExeFNKOGJHcQplbG4zbWh4WDU2cmpTOG5LZGk4MzRZSlNaV3VxUHZmWWUrbEV6Nk5laU1FMEo3dE80eWxmeWlPQ05ycnF3SnJnCjBXWTFEeDd4MHlZajdrN1NkUWVLVUVaZ3FjNUFuVitjNUQ2SjJTSTlGMnNoZWxGNWVvZjJOYkl2TmFNakpSRDgKb1FJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==';

Format:

Sample (Hex representation):

01 **(ID: 0x01)**
cd **(Pub. ID: 205)**
3d5c3a5c044d5c07f94ea2f5 **(IV)**
0001 **(256 RSA length little endian)**
47e81a1588e7d650b512d56e992ef5b1ce24050d64eb33626cdb695edb595c2b73f0205683ef9f84a6ebceb6e5f2384bd094caa47b3d8912bda5ddb03f7c2668501414639edc3fd9e47ddd6ab1cead3900699c7625dc35a6e85b696d9a4585a142fc7d99df6cdb685d555567a9fb69816996e776509f80ff360556c4d2b2819bbdd048ca3b6d30a70d40db28b40a3de6903ebfdf6adfd3d1674ba0dc1ec6adf39ac95fadece4e88a7b6ac598e8c58b639aa75ae27ee406caee1155bbc817e7014d24f69592715b63257124a067a326d0db7794540543c95492255438c280b6768662983983b5e82e67bc5371de391ce00c2e8c864e97a9aa9612acf977a19abd **RSA Enc. Key**
f7364edeba87bc2e3dd73c31f51e9898 **AES GCM TAG**
b92c412352e9d519bc2733 **Enc. PW**

Happy new year! 🎉

hahah this is my first and best new year gift on this year! Thank you man...! 🎉

As a test, I decided to deliberately mismatch key-id and valid pub-key values. There's at least 3 pub-keys/ids that are available/public - default/android fallback (41), android (205), and web (245). If your envelope is correct, but the versions mismatch, then you'll get HTTP 400 responses:

Do you happen to have the Public Key for the web (245) version? All I can find in the headers and code is an hex string ("f5a1fdb4e2e032e5d3b42c3350d69918eebdb640e2f9cc0fe1fc55cd7800cf30") which if translated to base64 gives "9aH9tOLgMuXTtCwzUNaZGO69tkDi+cwP4fxVzXgAzzA=" which is not a public key.

OMG its @mgp25! Maybe someday you'll unblock me 😄

Do someone has solved this using python?

pls someone help,
I see a solution, but how to implement it in c# or c++ or java or python ?

Don't RSA encrypt the public key as shown in the node.js code above.

The public key isn't encrypted. The key used for the AES-GCM encryption is encrypted here. This is in fact the result you get in the ek buffer.

The "updated" code loks like this:

const randKey = crypto.randomBytes(32);
  const iv = crypto.randomBytes(12);
  const rsaEncrypted = crypto.publicEncrypt(Buffer.from(ig.state.passwordEncryptionPubKey, 'base64').toString(), randKey);
  const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
  const time = Math.floor(Date.now() / 1000).toString();
  const aesEncrypted = concat(cipher.setAAD(Buffer.from(time)).update(password), cipher.final());
  const authTag = cipher.getAuthTag();
  const sizeBuffer = Buffer.alloc(2, 0);
  sizeBuffer.writeInt16LE(rsaEncrypted.byteLength, 0);
  return {
    time,
    encrypted: concat(
      Buffer.from([1, ig.state.passwordEncryptionKeyId]),
      iv,
      sizeBuffer,
      rsaEncrypted,
      authTag,
      aesEncrypted)
      .toString('base64'),
  };

There's still something wrong.

The only fix needed for Node.js was to set the right RSA-Padding.
The updated code can be found here.

Looking for a python port of the nodejs that @Killer-Awesome-Phantom posted. I attempted it (https://pastebin.com/raw/DURQVhTn) however I messed up somewhere.

do you know why this code don't work ?
return

"{"message": "There was an error with your request. Please try again.", "status": "fail"}"

ig-set-password-encryption-web-key-id: 245
ig-set-password-encryption-web-pub-key: f5a1fdb4e2e032e5d3b42c3350d69918eebdb640e2f9cc0fe1fc55cd7800cf30

and how i can convert web version hex to public key format accept in php ?

<?php
$Username = 'myuser';
$password='mypass';
const IG_LOGIN_ANDROID_PUBLIC_KEY= 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF1enRZOEZvUlRGRU9mK1RkTGlUdAplN3FIQXY1cmdBMmk5RkQ0YjgzZk1GK3hheW14b0xSdU5KTitRanJ3dnBuSm1LQ0QxNGd3K2w3TGQ0RHkvRHVFCkRiZlpKcmRRWkJIT3drS3RqdDdkNWlhZFdOSjdLczlBM0NNbzB5UktyZFBGU1dsS21lQVJsTlFrVXF0YkNmTzcKT2phY3ZYV2dJcGlqTkdJRVk4UkdzRWJWZmdxSmsrZzhuQWZiT0xjNmEwbTMxckJWZUJ6Z0hkYWExeFNKOGJHcQplbG4zbWh4WDU2cmpTOG5LZGk4MzRZSlNaV3VxUHZmWWUrbEV6Nk5laU1FMEo3dE80eWxmeWlPQ05ycnF3SnJnCjBXWTFEeDd4MHlZajdrN1NkUWVLVUVaZ3FjNUFuVitjNUQ2SjJTSTlGMnNoZWxGNWVvZjJOYkl2TmFNakpSRDgKb1FJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==';
  function encryptPassword(
        $password,
        $publicKeyId,
        $publicKey)
    {
        $key = openssl_random_pseudo_bytes(32);
        $iv = openssl_random_pseudo_bytes(12);
        $time = time();

        openssl_public_encrypt($key ,$encryptedAesKey, base64_decode($publicKey));
        $encrypted = openssl_encrypt($password, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, strval($time));

        $payload = base64_encode("\x01" | pack('n', intval($publicKeyId)) . $iv . pack('s', strlen($encryptedAesKey)) . $encryptedAesKey . $tag . $encrypted);

        return sprintf('#PWD_INSTAGRAM_BROWSER:6:%s:%s', $time, $payload);
    }
        $enc= encryptPassword($password,245,IG_LOGIN_ANDROID_PUBLIC_KEY);

$vars='username='.$Username.'&password='.$password.'&enc_password='.urlencode($enc).'&queryParams=%7B%7D&optIntoOneTap=false';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.instagram.com/accounts/login/ajax/");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
 'User-Agent: Mozilla/5.0 (Linux; Android 10; Z832 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Mobile Safari/537.36' ,
 'Accept: */*' ,
 'Accept-Language: en-US,en;q=0.5' ,
 'X-CSRFToken: 62Fvm60ukhKaYnxdS9sOKrANwHu1SqXp' ,
 'X-Instagram-AJAX: 138daaa28c25' ,
 'X-IG-App-ID: 1217981644879628' ,
 'X-IG-WWW-Claim: 0' ,
 'Content-Type: application/x-www-form-urlencoded' ,
 'X-Requested-With: XMLHttpRequest' ,
 'Origin: https://www.instagram.com' ,
 'Connection: keep-alive' ,
 'Referer: https://www.instagram.com/accounts/login/' ,
 'Cookie: ig_cb=1; ig_did=2E232D1A-7FE5-4412-9D9B-0AC072FD937C; csrftoken=62Fvm60ukhKaYnxdS9sOKrANwHu1SqXp; rur=VLL; mid=Xjg6kgABAAHOs8f6YUYvLc7XDa_S' ,
 'TE: Trailers'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

var_dump(  $server_output) ;
?>


const IG_LOGIN_ANDROID_PUBLIC_KEY= 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQk

https://github.com/dilame/instagram-private-api/issues/1010#issuecomment-569759860

do you know why this code don't work ?
return

The browser encryption is different. You have to use your browser to "reverse" that.

Update

As this issue-thread isn't an issue for the library anymore, it will be closed.
However, you'll still be able to discuss on the topic.

On Tue, Feb 18, 2020 at 8:28 PM dentrav12 notifications@github.com wrote:

@PappaPaj https://github.com/PappaPaj
I really sorry for this but have you been successful with Python
implementation?

I have edited and finished the implementation in python however it still
doesn’t seem to work as I get an error from Instagram.

Can you show yours resolve for web version by PHP? For sprintf('#PWD_INSTAGRAM_BROWSER:6:%s:%s', $time, $payload)

do you know why this code don't work ?
return

[code]
[code]

and how i can convert web version hex to public key format accept in php ?

[code]

Not working for me

@EgorBaklach In your case, the encryption is done for the Android app. The web app has a different encryption.

@PappaPaj

Looking for a python port of the nodejs that @Killer-Awesome-Phantom posted. I attempted it (https://pastebin.com/raw/DURQVhTn) however I messed up somewhere.

~Fix the problem in your code.~
~It's working as expected.~
https://github.com/unoemon/instagram-enc_passowrd-generator

sorry.
an unfinished work...

@unoemon hello, does your endpoint accept this enc_password? .. have a similar code .. but always get "There was an error with your request. Please try again."

@unoemon one moment .. you forgot about "time" ... in IG source this is additionalData, but what happened to him, that without him, one result, somewhere an error

moment two .. in the implementation for the web, we don’t pass iv (nonce), without it it’s impossible to do anything on the server side. right?

@bugsel
Sorry... that Python code is incomplete.
The Node.js version has works for me.
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

@bugsel
Sorry... that Python code is incomplete.
The Node.js version has works for me.
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

Why would you use WebCrypto. You aren't in the web. You are in node.js.

pls someone help,
I see a solution, but how to implement it in c# or c++ or java or python ?

have you found a solution?

have you found a solution?

You only need to figure out how to rsa-encrypt and encrypt with aes-gcm.
Example for C#:
RSA Encryption, AES-GCM

You only need to figure out how to _rsa-encrypt_ and _encrypt with aes-gcm_.
Example for C#:
RSA Encryption, AES-GCM

This is good, I will deal with it, I understand, but I do not understand what parameters to take for transmission. Or we can take them from here?
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

You only need to figure out how to _rsa-encrypt_ and _encrypt with aes-gcm_.
Example for C#:
RSA Encryption, AES-GCM

And why RSA if after looking at the example above and all the others there were used only AES-GM, BASE64?

And why RSA if after looking at the example above and all the others there were used only AES-GM, BASE64?

Depends on what you're trying to solve. Web and Android have a different encryption.

Depends on what you're trying to solve. Web and Android have a different encryption.

I didn't know, thank you) What do you need for the web? If there was a solution, please throw it off. Thank you in advance

What do you need for the web?

NaCl seal and AES-GCM. You don't need the array magic found in the solutions provided earlier. Try to figure out how this can be done efficiently.

NaCl seal and AES-GCM. You don't need the array magic found in the solutions provided earlier. Try to figure out how this can be done efficiently.

In other words, you can register without passing this parameter to pwd_instagram_browser, do I understand you correctly?

In other words, you can register without passing this parameter to pwd_instagram_browser, do I understand you correctly?

With "array magic", I'm refering to something like this: let f = 0; y[f] = 1, y[f += 1] = key_id, f += 1; which is valid, but is way simpler than it looks.

With "array magic", I'm refering to something like this: let f = 0; y[f] = 1, y[f += 1] = key_id, f += 1; which is valid, but is way simpler than it looks.

Is this information for creating "pwd_instagram_browser" or can I register without this parameter?

Is this information for creating "pwd_instagram_browser" or can I register without this parameter?

Ofc you need this. But this can be done much cleaner

Ofc you need this. But this can be done much cleaner

Please tell me how you can then implement it. I have been trying to do something for 5 days and nothing works

I don't want to pollute this thread with this conversation. You can message me on Discord (Nerix#8750) or Telegram (@nerixyz).

And to make it very simple. In the new Instagram this endpoint is gone. So you don't need it anymore.

And to make it very simple. In the new Instagram this endpoint is gone. So you don't need it anymore.

Which endpoint are you refering to?
There's no endpoint for password encryption. This would defeat the whole purpose of encrypting the password.

it was part of the https://www.instagram.com/accounts/login/ endpoint as a header as far as I know, but I don't see it anymore in the latest android version of the instagram app.

it was part of the https://www.instagram.com/accounts/login/ endpoint as a header as far as I know, but I don't see it anymore in the latest android version of the instagram app.

It's not in the header, it's in the body as enc_password.
This is controlled by ig_android_pwd_encrytpion and thus it can be remotely enabled.

Is this information for creating "pwd_instagram_browser" or can I register without this parameter?

you cant creat success without this parameter

Any updates on this? Looking for the web password encryption

Any updates on this? Looking for the web password encryption

You can check out this project (NodeJS): https://github.com/JuanFelipeChaparro/InstagramWebLogin

For everyone, so you don't have to look for yourself:

Web-Login-Encryption: Click here.
Android-Login-Encryption: Click here.

I have converted the code to python but IG says request failed. Anyone else working on it ?

Does anyone have the code convert to PHP. it will be helpful

Does anyone have the code convert to PHP. it will be helpful

https://github.com/dilame/instagram-private-api/issues/1010#issuecomment-569759860

Its android vertion and php base

Does anyone have the code convert to PHP. it will be helpful

#1010 (comment)

Its android vertion and php base

Thank you. Can you help me out a little bit?
I have this error openssl_public_encrypt(): key parameter is not a valid public key
on this line openssl_public_encrypt(): key parameter is not a valid public key

I have try public_key in https://www.instagram.com/data/shared_data/ and even the IG Android default public key (ID: 41): Public Key returned on API responses (ID: 205): all not work

Does anyone have the code convert to PHP. it will be helpful

#1010 (comment)
Its android vertion and php base

Thank you. Can you help me out a little bit?
I have this error openssl_public_encrypt(): key parameter is not a valid public key
on this line openssl_public_encrypt(): key parameter is not a valid public key

I have try public_key in https://www.instagram.com/data/shared_data/ and even the IG Android default public key (ID: 41): Public Key returned on API responses (ID: 205): all not work

same problem

PWD_INSTAGRAM_BROWSER:10:1590222650:AdNQAKnCrRPlehNkd6wEK/8SGUabxcRu77cDSzfYuM4kOOwqXu8LDIXSbHLInS6feku0uheTc6+zJQPZrWVx+uB/djEWSkseve7ypGv/nWxavh++RloGBLI86uz1aWy9b3deVGvt0SoyMGDYwqoy7TfQKCx7OLO8DA==

what about keys for PWD_INSTAGRAM_BROWSER:10 ???

Does anyone have the code convert to PHP. it will be helpful

#1010 (comment)
Its android vertion and php base

Thank you. Can you help me out a little bit?
I have this error openssl_public_encrypt(): key parameter is not a valid public key
on this line openssl_public_encrypt(): key parameter is not a valid public key

I have try public_key in https://www.instagram.com/data/shared_data/ and even the IG Android default public key (ID: 41): Public Key returned on API responses (ID: 205): all not work

Sorry, im not good at php

PWD_INSTAGRAM_BROWSER:10:1590222650:AdNQAKnCrRPlehNkd6wEK/8SGUabxcRu77cDSzfYuM4kOOwqXu8LDIXSbHLInS6feku0uheTc6+zJQPZrWVx+uB/djEWSkseve7ypGv/nWxavh++RloGBLI86uz1aWy9b3deVGvt0SoyMGDYwqoy7TfQKCx7OLO8DA==

what about keys for PWD_INSTAGRAM_BROWSER:10 ???

this is for web?

PWD_INSTAGRAM_BROWSER:10:1590222650:AdNQAKnCrRPlehNkd6wEK/8SGUabxcRu77cDSzfYuM4kOOwqXu8LDIXSbHLInS6feku0uheTc6+zJQPZrWVx+uB/djEWSkseve7ypGv/nWxavh++RloGBLI86uz1aWy9b3deVGvt0SoyMGDYwqoy7TfQKCx7OLO8DA==
what about keys for PWD_INSTAGRAM_BROWSER:10 ???

this is for web?

yes

ig-set-password-encryption-web-key-id: 211
ig-set-password-encryption-web-pub-key: e850d1a80186cefd9b50c38e2c614a55960c3873607da07101fb780f7f599678
ig-set-password-encryption-web-key-version: 10

Does anyone have a working Java version for mobile?
I tried to write one but keep getting 400's


Here's my code

private static Pair<Long, String> encryptPaswword(String password, String encryptionPubKey, String encryptionKeyId) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidCipherTextException, InvalidAlgorithmParameterException {
        byte[] passwordAsByte = password.getBytes();
        String decoededPubKey = new String(Base64.decode(encryptionPubKey, Base64.NO_WRAP), StandardCharsets.UTF_8);
        decoededPubKey = decoededPubKey.replace("-----BEGIN PUBLIC KEY-----", "");
        decoededPubKey = decoededPubKey.replace("-----END PUBLIC KEY-----", "");
        SecureRandom random = new SecureRandom();
        byte[] randKey = new byte[32];
        random.nextBytes(randKey);
        byte[] iv = new byte[12];
        random.nextBytes(iv);
        long date = new Date().getTime() / 1000;

        ByteBuffer header = ByteBuffer.allocate(2);
        header.put(Integer.valueOf(1).byteValue());
        header.put(Integer.valueOf(Integer.parseInt(encryptionKeyId)).byteValue());
        ByteBuffer timeAAD = ByteBuffer.allocate(10);
        timeAAD.put(String.valueOf(date).getBytes());

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicSpec);
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

        ByteBuffer sizeBuff = ByteBuffer.allocate(2);
        sizeBuff.put(Integer.valueOf(rsaEncrypted.length).byteValue());

        final Cipher gcmCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec parameterSpec = new GCMParameterSpec(16 * Byte.SIZE, iv);
        gcmCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(randKey, "AES"), parameterSpec);
        gcmCipher.updateAAD(timeAAD);
        byte[] gcmText= gcmCipher.doFinal(passwordAsByte);

        ByteBuffer result = ByteBuffer.allocate(2+12+2+256+gcmText.length);
        result.put(header);
        result.put(iv);
        result.put(sizeBuff);
        result.put(rsaEncrypted);
        result.put(Arrays.copyOfRange(gcmText, gcmText.length - (16 / Byte.SIZE), gcmText.length));
        result.put(Arrays.copyOfRange(gcmText, 0, gcmText.length - (16 / Byte.SIZE)));

        return new Pair(new Long(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
    }

OK got it to work using BouncyCastle..


if anyone needs a reference to Java code here it is

private static Pair<Long, String> encryptPassword(String password, String encryptionPubKey, String encryptionKeyId) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidCipherTextException, InvalidAlgorithmParameterException {
        byte[] passwordAsByte = password.getBytes();
        String decoededPubKey = new String(Base64.decode(encryptionPubKey, 0), StandardCharsets.UTF_8);
        decoededPubKey = decoededPubKey.replace("-----BEGIN PUBLIC KEY-----", "");
        decoededPubKey = decoededPubKey.replace("-----END PUBLIC KEY-----", "");

        SecureRandom random = new SecureRandom();
        byte[] randKey = new byte[32];
        random.nextBytes(randKey);
        byte[] iv = new byte[12];
        random.nextBytes(iv);
        String date = String.valueOf(new Date().getTime() / 1000);

        ByteBuffer header = ByteBuffer.allocate(2);
        header.put(Integer.valueOf(1).byteValue());
        header.put(Integer.valueOf(Integer.parseInt(encryptionKeyId)).byteValue());
        ByteBuffer timeAAD = ByteBuffer.allocate(10);
        timeAAD.put(date.getBytes());

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicSpec);
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

        ByteBuffer sizeBuff = ByteBuffer.allocate(2);
        sizeBuff.order(ByteOrder.LITTLE_ENDIAN);
        sizeBuff.putChar((char) rsaEncrypted.length);

        AEADParameters parameters = new AEADParameters(new KeyParameter(randKey), 128, iv, timeAAD.array());
        GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
        gcmEngine.init(true, parameters);
        byte[] gcmText = new byte[gcmEngine.getOutputSize(passwordAsByte.length)];
        int len = gcmEngine.processBytes(passwordAsByte, 0, passwordAsByte.length, gcmText, 0);
        gcmEngine.doFinal(gcmText, len);
        byte[] encPass = Arrays.copyOfRange(gcmText, 0, gcmText.length - 16);
        byte[] authTag = Arrays.copyOfRange(gcmText, gcmText.length - 16, gcmText.length);


        ByteBuffer result = ByteBuffer.allocate(header.position() + iv.length + sizeBuff.position() + rsaEncrypted.length + authTag.length + encPass.length);
        result.put(header.array());
        result.put(iv);
        result.put(sizeBuff.array());
        result.put(rsaEncrypted);
        result.put(authTag);
        result.put(encPass);

        return new Pair(new Long(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
    }

This password only works with a specific phone number, so somehow the number and password are compiled into one, the question is how?

PWD_INSTAGRAM:4:1590410299:AQjwpCXFeCb6SfvVbp8AAZPhmZol61lsiMbf94OKNozaO+ajlT5uksb2W34SmflzRbUHLraaKK2ax131IlrpiXKisshUAi/umn145ZASUvAchPaQ1IZQ4ujPJQX0tJ4aIQJbKxoWlsj0K2y8jL57DPwc+rwIJr6JxoLHJfMs4kvdnb9ZVMDV851Fq3482SrfXT4WLATlfYwEHyXSpJGJHzheLP5ygF5i89cWRubiH6WD2mE6cRwkCgWAPmXHINXSFMwUo2vdRJSDWh+oPvurfyQDuSQChHiWNHi2k10qmJJTL5Z3EgbfTEFtHXKIWw6pqgAzOcd8tFKNP1mAmmJJB7Wl1YBDnSclh/jj0XH9Nk9djgDmQANsEMPqdjJgAWGfrUQ+QwedQgI=

This password only works with a specific phone number, so somehow the number and password are compiled into one, the question is how?

PWD_INSTAGRAM:4:1590410299:AQjwpCXFeCb6SfvVbp8AAZPhmZol61lsiMbf94OKNozaO+ajlT5uksb2W34SmflzRbUHLraaKK2ax131IlrpiXKisshUAi/umn145ZASUvAchPaQ1IZQ4ujPJQX0tJ4aIQJbKxoWlsj0K2y8jL57DPwc+rwIJr6JxoLHJfMs4kvdnb9ZVMDV851Fq3482SrfXT4WLATlfYwEHyXSpJGJHzheLP5ygF5i89cWRubiH6WD2mE6cRwkCgWAPmXHINXSFMwUo2vdRJSDWh+oPvurfyQDuSQChHiWNHi2k10qmJJTL5Z3EgbfTEFtHXKIWw6pqgAzOcd8tFKNP1mAmmJJB7Wl1YBDnSclh/jj0XH9Nk9djgDmQANsEMPqdjJgAWGfrUQ+QwedQgI=

Where u see phone number? 1590410299? :D

This password only works with a specific phone number, so somehow the number and password are compiled into one, the question is how?

PWD_INSTAGRAM:4:1590410299:AQjwpCXFeCb6SfvVbp8AAZPhmZol61lsiMbf94OKNozaO+ajlT5uksb2W34SmflzRbUHLraaKK2ax131IlrpiXKisshUAi/umn145ZASUvAchPaQ1IZQ4ujPJQX0tJ4aIQJbKxoWlsj0K2y8jL57DPwc+rwIJr6JxoLHJfMs4kvdnb9ZVMDV851Fq3482SrfXT4WLATlfYwEHyXSpJGJHzheLP5ygF5i89cWRubiH6WD2mE6cRwkCgWAPmXHINXSFMwUo2vdRJSDWh+oPvurfyQDuSQChHiWNHi2k10qmJJTL5Z3EgbfTEFtHXKIWw6pqgAzOcd8tFKNP1mAmmJJB7Wl1YBDnSclh/jj0XH9Nk9djgDmQANsEMPqdjJgAWGfrUQ+QwedQgI=

Where u see phone number? 1590410299? :D

No, sry :D

phone number: +380996075827
password: 29usevap
encryption-key-id: 8
encryption-pub-key: LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUEzZWZSYWpodmRFRzR3MSsvM3lTYgpCdHlwckJjZ0Y1bjZrTFh6ZlhReHgreFN2MmFhemlvTWx2clBaZG53Y3hhcmJRVFZtamRYTnczejc0NUxSZFI1CjQwQ2ZCOU1NSmJKVlJnRGk2SG1FUzEwNms5b2REejhYemplNWFZa3FjZGZ4VjAvWUo5WGt3T3BDVGNhWkRoR0IKa3lXZUQxUEIrOW4rNityK2JUQ2p6Z1hLMm1lZElXak0rSVZTVklRWDdxZmVRalBwaGhLc2lsYTB1WllTR3FpZQpwVndBaUdFQnlmZW5Ca3k2SW5sMUowTERMZi90QWxSWUxac2JlcUlZeUdlbzdFcUd1M2hjWUNtcnVXRE1jRG5HCmxPQ3RlQ29zZXZld3VPVkc1TDZJTjNSVGVZR1VuN1h6enNwOTVaQzRmUVNCTnVCT2I0MmdhTDFCbHpCaW9WelIKUlFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==

If you pass this number and enc_password every time it will say what created the same account

This password only works with a specific phone number, so somehow the number and password are compiled into one, the question is how?

PWD_INSTAGRAM:4:1590410299:AQjwpCXFeCb6SfvVbp8AAZPhmZol61lsiMbf94OKNozaO+ajlT5uksb2W34SmflzRbUHLraaKK2ax131IlrpiXKisshUAi/umn145ZASUvAchPaQ1IZQ4ujPJQX0tJ4aIQJbKxoWlsj0K2y8jL57DPwc+rwIJr6JxoLHJfMs4kvdnb9ZVMDV851Fq3482SrfXT4WLATlfYwEHyXSpJGJHzheLP5ygF5i89cWRubiH6WD2mE6cRwkCgWAPmXHINXSFMwUo2vdRJSDWh+oPvurfyQDuSQChHiWNHi2k10qmJJTL5Z3EgbfTEFtHXKIWw6pqgAzOcd8tFKNP1mAmmJJB7Wl1YBDnSclh/jj0XH9Nk9djgDmQANsEMPqdjJgAWGfrUQ+QwedQgI=

Where u see phone number? 1590410299? :D

No, sry :D

phone number: +380996075827
password: 29usevap
encryption-key-id: 8
encryption-pub-key: LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUEzZWZSYWpodmRFRzR3MSsvM3lTYgpCdHlwckJjZ0Y1bjZrTFh6ZlhReHgreFN2MmFhemlvTWx2clBaZG53Y3hhcmJRVFZtamRYTnczejc0NUxSZFI1CjQwQ2ZCOU1NSmJKVlJnRGk2SG1FUzEwNms5b2REejhYemplNWFZa3FjZGZ4VjAvWUo5WGt3T3BDVGNhWkRoR0IKa3lXZUQxUEIrOW4rNityK2JUQ2p6Z1hLMm1lZElXak0rSVZTVklRWDdxZmVRalBwaGhLc2lsYTB1WllTR3FpZQpwVndBaUdFQnlmZW5Ca3k2SW5sMUowTERMZi90QWxSWUxac2JlcUlZeUdlbzdFcUd1M2hjWUNtcnVXRE1jRG5HCmxPQ3RlQ29zZXZld3VPVkc1TDZJTjNSVGVZR1VuN1h6enNwOTVaQzRmUVNCTnVCT2I0MmdhTDFCbHpCaW9WelIKUlFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==

If you pass this number and enc_password every time it will say what created the same account

If not correct, pass enc_password, response: {'nonce_valid': False, 'verified': False, 'errors': {'nonce': ["That code isn't valid. You can request a new one."]}, 'status': 'ok', 'error_type': 'invalid_nonce'}

Where can I get these two values? (encryptionPubKey, encryptionKeyId)

`private static Pair encryptPassword(String password, String encryptionPubKey, String encryptionKeyId) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidCipherTextException, InvalidAlgorithmParameterException {
byte[] passwordAsByte = password.getBytes();
String decoededPubKey = new String(Base64.decode(encryptionPubKey, 0), StandardCharsets.UTF_8);
decoededPubKey = decoededPubKey.replace("-----BEGIN PUBLIC KEY-----", "");
decoededPubKey = decoededPubKey.replace("-----END PUBLIC KEY-----", "");

    SecureRandom random = new SecureRandom();
    byte[] randKey = new byte[32];
    random.nextBytes(randKey);
    byte[] iv = new byte[12];
    random.nextBytes(iv);
    String date = String.valueOf(new Date().getTime() / 1000);

    ByteBuffer header = ByteBuffer.allocate(2);
    header.put(Integer.valueOf(1).byteValue());
    header.put(Integer.valueOf(Integer.parseInt(encryptionKeyId)).byteValue());
    ByteBuffer timeAAD = ByteBuffer.allocate(10);
    timeAAD.put(date.getBytes());

    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(publicSpec);
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

    ByteBuffer sizeBuff = ByteBuffer.allocate(2);
    sizeBuff.order(ByteOrder.LITTLE_ENDIAN);
    sizeBuff.putChar((char) rsaEncrypted.length);

    AEADParameters parameters = new AEADParameters(new KeyParameter(randKey), 128, iv, timeAAD.array());
    GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
    gcmEngine.init(true, parameters);
    byte[] gcmText = new byte[gcmEngine.getOutputSize(passwordAsByte.length)];
    int len = gcmEngine.processBytes(passwordAsByte, 0, passwordAsByte.length, gcmText, 0);
    gcmEngine.doFinal(gcmText, len);
    byte[] encPass = Arrays.copyOfRange(gcmText, 0, gcmText.length - 16);
    byte[] authTag = Arrays.copyOfRange(gcmText, gcmText.length - 16, gcmText.length);


    ByteBuffer result = ByteBuffer.allocate(header.position() + iv.length + sizeBuff.position() + rsaEncrypted.length + authTag.length + encPass.length);
    result.put(header.array());
    result.put(iv);
    result.put(sizeBuff.array());
    result.put(rsaEncrypted);
    result.put(authTag);
    result.put(encPass);

    return new Pair(new Long(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
}`

You need to perform a request before hand.
See: https://github.com/dilame/instagram-private-api/blob/c018ee130dd13aaae1d1c97d5d40f22ef25c1f6f/src/repositories/qe.repository.ts

This password only works with a specific phone number, so somehow the number and password are compiled into one, the question is how?

PWD_INSTAGRAM:4:1590410299:AQjwpCXFeCb6SfvVbp8AAZPhmZol61lsiMbf94OKNozaO+ajlT5uksb2W34SmflzRbUHLraaKK2ax131IlrpiXKisshUAi/umn145ZASUvAchPaQ1IZQ4ujPJQX0tJ4aIQJbKxoWlsj0K2y8jL57DPwc+rwIJr6JxoLHJfMs4kvdnb9ZVMDV851Fq3482SrfXT4WLATlfYwEHyXSpJGJHzheLP5ygF5i89cWRubiH6WD2mE6cRwkCgWAPmXHINXSFMwUo2vdRJSDWh+oPvurfyQDuSQChHiWNHi2k10qmJJTL5Z3EgbfTEFtHXKIWw6pqgAzOcd8tFKNP1mAmmJJB7Wl1YBDnSclh/jj0XH9Nk9djgDmQANsEMPqdjJgAWGfrUQ+QwedQgI=

Where u see phone number? 1590410299? :D

No, sry :D
phone number: +380996075827
password: 29usevap
encryption-key-id: 8
encryption-pub-key: LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUEzZWZSYWpodmRFRzR3MSsvM3lTYgpCdHlwckJjZ0Y1bjZrTFh6ZlhReHgreFN2MmFhemlvTWx2clBaZG53Y3hhcmJRVFZtamRYTnczejc0NUxSZFI1CjQwQ2ZCOU1NSmJKVlJnRGk2SG1FUzEwNms5b2REejhYemplNWFZa3FjZGZ4VjAvWUo5WGt3T3BDVGNhWkRoR0IKa3lXZUQxUEIrOW4rNityK2JUQ2p6Z1hLMm1lZElXak0rSVZTVklRWDdxZmVRalBwaGhLc2lsYTB1WllTR3FpZQpwVndBaUdFQnlmZW5Ca3k2SW5sMUowTERMZi90QWxSWUxac2JlcUlZeUdlbzdFcUd1M2hjWUNtcnVXRE1jRG5HCmxPQ3RlQ29zZXZld3VPVkc1TDZJTjNSVGVZR1VuN1h6enNwOTVaQzRmUVNCTnVCT2I0MmdhTDFCbHpCaW9WelIKUlFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==
If you pass this number and enc_password every time it will say what created the same account

If not correct, pass enc_password, response: {'nonce_valid': False, 'verified': False, 'errors': {'nonce': ["That code isn't valid. You can request a new one."]}, 'status': 'ok', 'error_type': 'invalid_nonce'}

maybe need password + sms_code compile?

`const crypto = require('crypto');

const getEncPassword = (password, pubKey, keyID) => {
const plainKey = Buffer.from(pubKey, 'base64').toString();
const randKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(12);
const resEncrypted = crypto.publicEncrypt(plainKey, randKey);
const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
const time = Math.floor(Date.now() / 1000).toString();
cipher.setAAD(Buffer.from(time));
const aesEncrypted = Buffer.concat([cipher.update(password, 'utf8'), cipher.final()]);
const sizeBuffer = Buffer.alloc(2, 0);
sizeBuffer.writeInt16LE(resEncrypted.byteLength, 0);
const authTag = cipher.getAuthTag();
const pass = Buffer.concat(
[Buffer.from([1, keyID]),
iv,
sizeBuffer,
resEncrypted, aesEncrypted, authTag])
.toString('base64')
console.log(#PWD_INSTAGRAM:4:${time}:${pass})
}`

Where can I get these two values? (pubKey, keyID)

Is there any code to request value in JAVA language?

I am curious about the solution. H
you can get this two values from http request response

https://www.instagram.com/data/shared_data/

"encryption":{"key_id":"13","public_key":"455c2c7b4e4a873c40f46b8e2bdfd90214591c3110b3c7ab7458818af3c59649","version":"10"}

Is the value printed here correct? (key_id, public_key)

https://www.instagram.com/data/shared_data/

"encryption":{"key_id":"13","public_key":"455c2c7b4e4a873c40f46b8e2bdfd90214591c3110b3c7ab7458818af3c59649","version":"10"}

Is the value printed here correct? (key_id, public_key)

yes

thank you for the reply.

But there is one more question.

Isn't it mobile version 4? The link has a value of 10.

The result is the same even if you try it on your mobile phone.

thank you for the reply.

But there is one more question.

Isn't it mobile version 4? The link has a value of 10.

The result is the same even if you try it on your mobile phone.

version 4 is ig android app

hi i problem java code for generate enc_password

OK, BouncyCastle을 사용하여 작동했습니다.

누구나 Java 코드에 대한 참조가 필요한 경우

The error is not resolved. Please help.

E/AndroidRuntime: FATAL EXCEPTION: Thread-3 Process: com.abs.likeming, PID: 11874 java.lang.IllegalArgumentException: bad base-64 at android.util.Base64.decode(Base64.java:161) at android.util.Base64.decode(Base64.java:136) at android.util.Base64.decode(Base64.java:118) at com.abs.likeming.MainActivity.encryptPassword(MainActivity.java:314) at com.abs.likeming.MainActivity.access$100(MainActivity.java:75) at com.abs.likeming.MainActivity$4$1.run(MainActivity.java:172)

public_key , key_id , version : First of all, it is the source from which three data were imported.
The test result version is 10.

`

                        hc = new DefaultHttpClient();                       
                        HttpGet gets = new HttpGet("https://www.instagram.com/data/shared_data/");
                        org.apache.http.HttpResponse response1 = hc.execute(gets);
                        String json = EntityUtils.toString(response1.getEntity());
                        JSONObject jObject = new JSONObject(json);
                        final String public_key = jObject.getJSONObject("encryption").getString("public_key");
                        final String key_id = jObject.getJSONObject("encryption").getString("key_id");
                        final String version = jObject.getJSONObject("encryption").getString("version");
                        Pair<Long, String> result1 = encryptPassword(pw.getText().toString(), public_key, key_id);
                        String time = result1.first.toString();
                        String code256 = result1.second;


                        hc = new DefaultHttpClient();
                        HttpPost post = new HttpPost("https://www.instagram.com/accounts/login/ajax/");
                        List<NameValuePair> data = new ArrayList<NameValuePair>();

                        data.add(new BasicNameValuePair("username", id.getText().toString()));
                        data.add(new BasicNameValuePair("enc_password", "#PWD_INSTAGRAM:10:" + time + ":" + code256));
                        post.addHeader("X-CSRFToken", csrftoken);
                        post.addHeader("referer", "https://www.instagram.com/");
                        post.addHeader("cookie", "csrftoken=" + csrftoken + ";mid=" + mid);
                        post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

`

   private static Pair<Long, String> encryptPassword(String password, String encryptionPubKey, String encryptionKeyId)throwsNoSuchAlgorithmException,InvalidKeySpecException,NoSuchPaddingException,InvalidKeyException,BadPaddingException,IllegalBlockSizeException,InvalidCipherTextException, 
    InvalidAlgorithmParameterException {

    byte[] passwordAsByte = password.getBytes();
    String decoededPubKey = new String(Base64.decode(encryptionPubKey,0),StandardCharsets.UTF_8);


    decoededPubKey = decoededPubKey.replace("-----BEGIN PUBLIC KEY-----", "");
    decoededPubKey = decoededPubKey.replace("-----END PUBLIC KEY-----", "");
    SecureRandom random = new SecureRandom();
    byte[] randKey = new byte[32];
    random.nextBytes(randKey);
    byte[] iv = new byte[12];
    random.nextBytes(iv);
    //String date = String.valueOf(new Date().getTime() / 1000);
    Long tsLong = System.currentTimeMillis()/1000;
    String date = tsLong.toString();

    ByteBuffer header = ByteBuffer.allocate(2);
    header.put(Integer.valueOf(1).byteValue());
    header.put(Integer.valueOf(Integer.parseInt(encryptionKeyId)).byteValue());
    ByteBuffer timeAAD = ByteBuffer.allocate(10);
    timeAAD.put(date.getBytes());

    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(publicSpec);
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

    ByteBuffer sizeBuff = ByteBuffer.allocate(2);
    sizeBuff.order(ByteOrder.LITTLE_ENDIAN);
    sizeBuff.putChar((char) rsaEncrypted.length);

    AEADParameters parameters = new AEADParameters(new KeyParameter(randKey), 128, iv, timeAAD.array());
    GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
    gcmEngine.init(true, parameters);
    byte[] gcmText = new byte[gcmEngine.getOutputSize(passwordAsByte.length)];
    int len = gcmEngine.processBytes(passwordAsByte, 0, passwordAsByte.length, gcmText, 0);
    gcmEngine.doFinal(gcmText, len);
    byte[] encPass = Arrays.copyOfRange(gcmText, 0, gcmText.length - 16);
    byte[] authTag = Arrays.copyOfRange(gcmText, gcmText.length - 16, gcmText.length);


    ByteBuffer result = ByteBuffer.allocate(header.position() + iv.length + sizeBuff.position() + rsaEncrypted.length + authTag.length + encPass.length);
    result.put(header.array());
    result.put(iv);
    result.put(sizeBuff.array());
    result.put(rsaEncrypted);
    result.put(authTag);
    result.put(encPass);

    return new Pair(new Long(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
}`

@alsrl304 (and @ the others) Please, wrap your code in an expandable section, so the issue doesn't get polluted (there are 100+ comments now).

Also, don't just comment here without reading the other comments. If you had done this, you would've seen this comment and figured, there's a difference between the Web and Android API.

@itsMoji to create an account, apparently not only the password is transmitted

Is there any code in C #?

Is there any code in C #?

I'm trying to do it for web auth. Using libsodium-net for sealedbox and bouncecastle for aes-gcm encrypt. But still cant complete, because got 200 answer from server like this:
{"authenticated": false, "user": false, "status": "ok"}
Right string from browser:
#PWD_INSTAGRAM_BROWSER:10:1590846060:AdxQACM5pu1DZfAmVR8/Ohndkkl92Z0fVBrFLL6NNokoWf8CqgE4nZJcRcsgkZ/57MXd8am0kgDiI9823taMfwYJhdNCmgLwkUF1/A5fiavg4wZMIAN15k8BnJvujW8xdfPR+PG2Xenwi4ecDw==
Bad string from my query:
#PWD_INSTAGRAM_BROWSER:10:1590845948:AdxQAPy24qck5pel4gAaF1GZpeRHE3ITD5uXfYq74Nsz7S5TLfZ9Rirgv/yRIWwqCJSPsRkV8ZVVbf7DBubMDVk4os0CsNun1Qdf3yDIzRt+XYDi2CrlDYoSc2rc6ExSNS8PDPhbpA6wcbgRdw==

Header of string form this node.js code:

Buffer.from([
          1,
          Number(publicKeyId),
          encryptedKey.byteLength & 255,
          (encryptedKey.byteLength >> 8) & 255,
        ])

is same but I'm not sure about the other part...

@itsMoji to create an account, apparently not only the password is transmitted

You get this problem solved?

@itsMoji to create an account, apparently not only the password is transmitted

You get this problem solved?

nope

I am trying to create web version using java. However i seem to fail generate public key from returned string..

The api call returns:
98c018614437ea1022c62e532acf7dc3d268b393f0749aca68e6f39cfc998e4c

Using basic code in native java:

        byte[] encodedPublicKey = Base64.decodeBase64(key);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedPublicKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        this.key = kf.generatePublic(spec);

Throws

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=71, too big.

Has anyone tried to do it in java? How do you parse this public key?

Hello
Is there any solve for this ?
I need a library or a solution on how to generate enc_password for Instagram web login

Hello
Is there any solve for this ?
I need a library or a solution on how to generate enc_password for Instagram web login

If Key Version is 0 you can send plain text password, example: #PWD_INSTAGRAM_BROWSER:0:0:myawesomepassword

What kind of public key is returned from calling https://www.instagram.com/data/shared_data/? Its 64bytes hexa string, when you create array of bytes from that its 32 bytes long and thus is too short for RSA public key, what kind of key is that?

What kind of public key is returned from calling https://www.instagram.com/data/shared_data/? Its 64bytes hexa string, when you create array of bytes from that its 32 bytes long and thus is too short for RSA public key, what kind of key is that?

Whats the point on encrypting password if u can send it in plain text using keyversion 0 ?

What kind of public key is returned from calling https://www.instagram.com/data/shared_data/? Its 64bytes hexa string, when you create array of bytes from that its 32 bytes long and thus is too short for RSA public key, what kind of key is that?

Whats the point on encrypting password if u can send it in plain text using keyversion 0 ?

Yes thank you.
This works.
I found it on another issue too but it's used as work around not long term solution.
Finding this does not mean that the problem is solved.

What kind of public key is returned from calling https://www.instagram.com/data/shared_data/? Its 64bytes hexa string, when you create array of bytes from that its 32 bytes long and thus is too short for RSA public key, what kind of key is that?

Whats the point on encrypting password if u can send it in plain text using keyversion 0 ?

Well if using keyversion 0 is long term solution fine, but im also curious

I also tried it using version0 but didnt work

Does anybody have the code for mobile? The encryption algorithm is different, it sends the public key as base 64 and using the node.js script provided above it gives me a key error as it is not a valid hex string, even through i've parsed it from the certificate and converted it to hex

@bugsel
Sorry... that Python code is incomplete.
The Node.js version has works for me.
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

Python working code for ig app:

import datetime
import base64
import struct
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA


def encrypt_password(key_id, pub_key, password):
    key = Random.get_random_bytes(32)
    iv = Random.get_random_bytes(12)
    time = int(datetime.datetime.now().timestamp())

    pubkey = base64.b64decode(pub_key)

    rsa_key = RSA.importKey(pubkey)
    rsa_cipher = PKCS1_v1_5.new(rsa_key)
    encrypted_key = rsa_cipher.encrypt(key)

    aes = AES.new(key, AES.MODE_GCM, nonce=iv)
    aes.update(str(time).encode('utf-8'))

    encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password, 'utf-8'))

    encrypted = bytes([1,
                       key_id,
                       *list(iv),
                       *list(struct.pack('<h', len(encrypted_key))),
                       *list(encrypted_key),
                       *list(cipher_tag),
                       *list(encrypted_password)])
    encrypted = base64.b64encode(encrypted).decode('utf-8')

    return f'#PWD_INSTAGRAM:4:{time}:{encrypted}'

this is a java version

``` java
String time = String.valueOf(System.currentTimeMillis()/1000);
int key = 64;
String pkey = "555026eac0a4d140916813b6e0fa18acf72fde978f212ffd61207def77e26065";
int overheadLength = 48;
byte[] pkeyArray = new byte[pkey.length() / 2];
for (int i = 0; i < pkeyArray.length; i++) {
int index = i * 2;
int j = Integer.parseInt(pkey.substring(index, index + 2), 16);
pkeyArray[i] = (byte) j;
}

byte [] y = new byte[password.length()+36+16+overheadLength];

int f = 0;
y[f] = 1;
y[f += 1] = (byte)key;
f += 1;

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);

// Generate Key
SecretKey secretKey = keyGenerator.generateKey();
byte[] IV = new byte[12];

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
cipher.updateAAD(time.getBytes());

byte [] sealed = SealedBoxUtility.crypto_box_seal(secretKey.getEncoded(),pkeyArray);
byte[] cipherText = cipher.doFinal(password.getBytes());
y[f] = (byte) (255 & sealed.length);
y[f + 1] = (byte) (sealed.length >> 8 & 255);
f += 2;
for(int j=f;j y[j] = sealed[j-f];
}
f += 32;
f += overheadLength;

byte [] c = Arrays.copyOfRange(cipherText,cipherText.length -16,cipherText.length);
byte [] h = Arrays.copyOfRange(cipherText,0,cipherText.length - 16);

for(int j=f;j y[j] = c[j-f];
}
f += 16;
for(int j=f;j y[j] = h[j-f];
}
String encPassword = Base64.getEncoder().encodeToString(y);
return "#PWD_INSTAGRAM_BROWSER:10:"+time+":"+encPassword
````

The SealedBoxUtility is from

https://stackoverflow.com/questions/42456624/how-can-i-create-or-open-a-libsodium-compatible-sealed-box-in-pure-java

@bugsel
Sorry... that Python code is incomplete.
The Node.js version has works for me.
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

Python working code for ig app:

import datetime
import base64
import struct
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA


def encrypt_password(key_id, pub_key, password):
    key = Random.get_random_bytes(32)
    iv = Random.get_random_bytes(12)
    time = int(datetime.datetime.now().timestamp())

    pubkey = base64.b64decode(pub_key)

    rsa_key = RSA.importKey(pubkey)
    rsa_cipher = PKCS1_v1_5.new(rsa_key)
    encrypted_key = rsa_cipher.encrypt(key)

    aes = AES.new(key, AES.MODE_GCM, nonce=iv)
    aes.update(str(time).encode('utf-8'))

    encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password, 'utf-8'))

    encrypted = bytes([1,
                       key_id,
                       *list(iv),
                       *list(struct.pack('<h', len(encrypted_key))),
                       *list(encrypted_key),
                       *list(cipher_tag),
                       *list(encrypted_password)])
    encrypted = base64.b64encode(encrypted).decode('utf-8')

    return f'#PWD_INSTAGRAM:4:{time}:{encrypted}'

Thanks for the code but I was unable to proceed with the RSA encryption.

using:
public_key = "20d21258fcb87159236eee2a011fb4be65d949c3815eab79e1c830882a2dfc6e"
on:
pubkey = base64.b64decode(pub_key)
returns:
b'xdbGvxd7n|}xc6xfcxef^}xdb~x9eyxedx9axd3]_ox86xdexebx97}xe3xd77xf3^^ixbexfd{W

step:
rsa_key = RSA.importKey(pubkey)
fails with:
ValueError: RSA key format is not supported

--

Am I missing something?

@bugsel
Sorry... that Python code is incomplete.
The Node.js version has works for me.
https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

Python working code for ig app:

import datetime
import base64
import struct
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA


def encrypt_password(key_id, pub_key, password):
    key = Random.get_random_bytes(32)
    iv = Random.get_random_bytes(12)
    time = int(datetime.datetime.now().timestamp())

    pubkey = base64.b64decode(pub_key)

    rsa_key = RSA.importKey(pubkey)
    rsa_cipher = PKCS1_v1_5.new(rsa_key)
    encrypted_key = rsa_cipher.encrypt(key)

    aes = AES.new(key, AES.MODE_GCM, nonce=iv)
    aes.update(str(time).encode('utf-8'))

    encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password, 'utf-8'))

    encrypted = bytes([1,
                       key_id,
                       *list(iv),
                       *list(struct.pack('<h', len(encrypted_key))),
                       *list(encrypted_key),
                       *list(cipher_tag),
                       *list(encrypted_password)])
    encrypted = base64.b64encode(encrypted).decode('utf-8')

    return f'#PWD_INSTAGRAM:4:{time}:{encrypted}'

This is not working. I have this message: "Oops, an error occurred."
id: "169"
key: "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF1dmtwUmcvNlpQV0hPM1lEclpxegpCN1NGNHkwL0Nhc1dDME9yNG9wYkMrOEs0MDJrMEZZRWEwQ1AyRE5VdjBrZTB4UFVYdnFwUXFhaERXSUlvOUI0Clk3RlFEOS9kbjZoWHk1SU1CUy9URnZ1em9ZNVpKUlhVd21yVVE5QW5oUnVLMGtUSTVjUjI3eXBYeDI3cjBwV0sKWXpROUdmMm9hTmg3N3lLTzB1RUtiTUZGUkFNMFBqQzRjUHNEU0RWVUNNeUt5cy94NVJCa3MxaVlLdFlQaEw0cQp6Vys3bHROYXpGY09QcThYOW1lR01XbVdaL3ZNWG1GeHM2QWp6ZGsreEt5aC9QSFRQQW1neklKcW9xNE1xN2l5Cm9ZaHpmVXo0M2RWb3lEd1BhNm5LcmpoMFdESlljWHFnTmZuVnNLbmQ2cXBnU3pvendOb0s0bFMyS0pxUExmU2YKZlFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg=="

This is a working code for python.

import base64
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_v1_5
import datetime
import struct
import requests

from Cryptodome.PublicKey import RSA

def main():
    print(encpass())

def encpass():
    password = "TESTPASSWORD"
    publickeyid, publickey = get_publickey_details("", "")
    session_key = get_random_bytes(32)
    iv = bytearray(12)
    time = str(int(datetime.datetime.now().timestamp()))
    decoded_publickey = base64.b64decode(publickey.encode())
    recipient_key = RSA.import_key(decoded_publickey)
    cipher_rsa = PKCS1_v1_5.new(recipient_key)
    enc_session_key = cipher_rsa.encrypt(session_key)
    cipher_aes = AES.new(session_key, AES.MODE_GCM, iv)
    cipher_aes.update(time.encode())
    ciphertext, tag = cipher_aes.encrypt_and_digest(password.encode("utf8"))
    payload = base64.b64encode((b"\x01\x00" + publickeyid.to_bytes(2, byteorder='big') + iv + len(enc_session_key).to_bytes(2, byteorder='big') + enc_session_key + tag + ciphertext))
    return f"#PWD_INSTAGRAM:4:{time}:{payload.decode()}"

def get_publickey_details(publickeyid, publickey):
    r = requests.get('https://i.instagram.com/api/v1/qe/sync/')
    publickeyid = int(r.headers['ig-set-password-encryption-key-id'])
    publickey = r.headers['ig-set-password-encryption-pub-key']
    return (publickeyid, publickey)


if __name__ == '__main__':
    main()

You can easily modify it to your code

Example Request

signed_body=SIGNATURE.{"jazoest":"","country_codes":"","phone_id":"","enc_password":":","username":"","adid":"","guid":"","device_id":"","google_tokens":"[]","login_attempt_count":""}

Example Response

{"logged_in_user": {"pk": , "username": "", "full_name": "", "is_private": , "profile_pic_url": "", "profile_pic_id": "", "is_verified": , "has_anonymous_profile_picture": , "can_boost_post": , "is_business": , "account_type": , "professional_conversion_suggested_account_type": , "is_call_to_action_enabled": , "can_see_organic_insights": , "show_insights_terms": , "total_igtv_videos": , "reel_auto_archive": "", "has_placed_orders": , "allowed_commenter_type": "", "nametag": , "is_using_unified_inbox_for_direct": , "interop_messaging_user_fbid": , "can_see_primary_country_in_settings": , "allow_contacts_sync": , "phone_number": ""}, "status": ""}

This is a working code for python.

import base64
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_v1_5
import datetime
import struct
import requests

from Cryptodome.PublicKey import RSA

def main():
    print(encpass())

def encpass():
    password = "TESTPASSWORD"
    publickeyid, publickey = get_publickey_details("", "")
    session_key = get_random_bytes(32)
    iv = bytearray(12)
    time = str(int(datetime.datetime.now().timestamp()))
    decoded_publickey = base64.b64decode(publickey.encode())
    recipient_key = RSA.import_key(decoded_publickey)
    cipher_rsa = PKCS1_v1_5.new(recipient_key)
    enc_session_key = cipher_rsa.encrypt(session_key)
    cipher_aes = AES.new(session_key, AES.MODE_GCM, iv)
    cipher_aes.update(time.encode())
    ciphertext, tag = cipher_aes.encrypt_and_digest(password.encode("utf8"))
    payload = base64.b64encode((b"\x01\x00" + publickeyid.to_bytes(2, byteorder='big') + iv + len(enc_session_key).to_bytes(2, byteorder='big') + enc_session_key + tag + ciphertext))
    return f"#PWD_INSTAGRAM:4:{time}:{payload.decode()}"

def get_publickey_details(publickeyid, publickey):
    r = requests.get('https://i.instagram.com/api/v1/qe/sync/')
    publickeyid = int(r.headers['ig-set-password-encryption-key-id'])
    publickey = r.headers['ig-set-password-encryption-pub-key']
    return (publickeyid, publickey)


if __name__ == '__main__':
    main()

You can easily modify it to your code

Example Request

signed_body=SIGNATURE.{"jazoest":"","country_codes":"","phone_id":"","enc_password":":","username":"","adid":"","guid":"","device_id":"","google_tokens":"[]","login_attempt_count":""}

Example Response

{"logged_in_user": {"pk": , "username": "", "full_name": "", "is_private": , "profile_pic_url": "", "profile_pic_id": "", "is_verified": , "has_anonymous_profile_picture": , "can_boost_post": , "is_business": , "account_type": , "professional_conversion_suggested_account_type": , "is_call_to_action_enabled": , "can_see_organic_insights": , "show_insights_terms": , "total_igtv_videos": , "reel_auto_archive": "", "has_placed_orders": , "allowed_commenter_type": "", "nametag": , "is_using_unified_inbox_for_direct": , "interop_messaging_user_fbid": , "can_see_primary_country_in_settings": , "allow_contacts_sync": , "phone_number": ""}, "status": ""}

Is it ok for API (not WEB) registering? I have error

{"message": "There was an error with your request. Please try again.", "status": "fail"}

This is a working code for python.

import base64
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_v1_5
import datetime
import struct
import requests

from Cryptodome.PublicKey import RSA

def main():
    print(encpass())

def encpass():
    password = "TESTPASSWORD"
    publickeyid, publickey = get_publickey_details("", "")
    session_key = get_random_bytes(32)
    iv = bytearray(12)
    time = str(int(datetime.datetime.now().timestamp()))
    decoded_publickey = base64.b64decode(publickey.encode())
    recipient_key = RSA.import_key(decoded_publickey)
    cipher_rsa = PKCS1_v1_5.new(recipient_key)
    enc_session_key = cipher_rsa.encrypt(session_key)
    cipher_aes = AES.new(session_key, AES.MODE_GCM, iv)
    cipher_aes.update(time.encode())
    ciphertext, tag = cipher_aes.encrypt_and_digest(password.encode("utf8"))
    payload = base64.b64encode((b"\x01\x00" + publickeyid.to_bytes(2, byteorder='big') + iv + len(enc_session_key).to_bytes(2, byteorder='big') + enc_session_key + tag + ciphertext))
    return f"#PWD_INSTAGRAM:4:{time}:{payload.decode()}"

def get_publickey_details(publickeyid, publickey):
    r = requests.get('https://i.instagram.com/api/v1/qe/sync/')
    publickeyid = int(r.headers['ig-set-password-encryption-key-id'])
    publickey = r.headers['ig-set-password-encryption-pub-key']
    return (publickeyid, publickey)


if __name__ == '__main__':
    main()

You can easily modify it to your code

Example Request

signed_body=SIGNATURE.{"jazoest":"","country_codes":"","phone_id":"","enc_password":":","username":"","adid":"","guid":"","device_id":"","google_tokens":"[]","login_attempt_count":""}

Example Response

{"logged_in_user": {"pk": , "username": "", "full_name": "", "is_private": , "profile_pic_url": "", "profile_pic_id": "", "is_verified": , "has_anonymous_profile_picture": , "can_boost_post": , "is_business": , "account_type": , "professional_conversion_suggested_account_type": , "is_call_to_action_enabled": , "can_see_organic_insights": , "show_insights_terms": , "total_igtv_videos": , "reel_auto_archive": "", "has_placed_orders": , "allowed_commenter_type": "", "nametag": , "is_using_unified_inbox_for_direct": , "interop_messaging_user_fbid": , "can_see_primary_country_in_settings": , "allow_contacts_sync": , "phone_number": ""}, "status": ""}

Is it ok for API (not WEB) registering? I have error

{"message": "There was an error with your request. Please try again.", "status": "fail"}

It is okay to use for API only (Tested on 25th June 2020) , please make sure you send requests as shown in example. There is no Signature Key used anymore.

signed_body=SIGNATURE.%7B%22jazoest%22%3A%22%22%2C%22country_codes%22%3A%22%22%2C%22phone_id%22%3A%22%22%2C%22enc_password%22%3A%22%3A%22%2C%22username%22%3A%22%22%2C%22adid%22%3A%22%22%2C%22guid%22%3A%22%22%2C%22device_id%22%3A%22%22%2C%22google_tokens%22%3A%22%5B%5D%22%2C%22login_attempt_count%22%3A%22%22%7D

Regards

about signature key i know bro :( but i cant reg, its problem that i say

Well I have checked it for login only , if by saying reg you mean creating account, I havent checked that and would not know whats wrong without checking your code.

Hey guys, this is web enc_password api:

https://leesoar.com/api-v1/ig?pub_key=20ed90203c457a2f9efc20820c2452403bff6424de39ff9cc928a751e07f6915&pub_id=229&pwd=xxx&t=1596703337&secret_key=a9ad0489a73146c68ec514ffce5cbaba

the secret_key have 200 times.

  • "t" is timestamp
  • "pwd" is password
  • "version" is pub_version, and default is 10
  • "action" default is "enc_password"

It returns:
{ "code": 1, "message": "ok", "enc_password": "#PWD_INSTAGRAM_BROWSER:10:1596703337:AQpQAH4W1vHVVa7730diM49fhY5Cn0CsgfGsZ5zA613WkRJDn3ujkqqwEdtnV7BrjgJsW3zinQ1OrSnTdgU2We72gWztHxM7OW2NSfvVR/4AGuCZGbR8mpk30wEzP4Z9tPLfxmr/o3Nmk6v7", "pub_key": "20ed90203c457a2f9efc20820c2452403bff6424de39ff9cc928a751e07f6915", "pub_id": "229", "pwd": "xxx", "version": 10, "t": "1596703337" }

@Leesoar
What you mean? Where can I get the secret_key and do you know the logic to encode behind this?

the secret_key have 200 times.

@Leesoar
What you mean? Where can I get the secret_key and do you know the logic to encode behind this?

the secret_key have 200 times.

I'll give you a free secret_key if you need it.
mailto: [email protected], thanks.

Hey guys, this is web enc_password api:

This is just unnecessary. In this thread are multiple solutions. And if you have a basic understanding of JavaScript, you can easily reverse engineer the algorithm. Open your browsers debugger, try to log in, in the sources, select www.instagram.com > static/bundles/... > EncryptionUtils.js > first item. In contrast to android you have a much easier way to debug and even prettify the code (bottom left). You can inspect and step through the entire process. The only info you need is that seal refers to NaCl's sealed box.

If this isn't free, then it's just a scam imo.

Hey guys, this is web enc_password api:

This is just unnecessary. In this thread are multiple solutions. And if you have a basic understanding of JavaScript, you can easily reverse engineer the algorithm. Open your browsers debugger, try to log in, in the sources, select www.instagram.com > static/bundles/... > EncryptionUtils.js > first item. In contrast to android you have a much easier way to debug and even prettify the code (bottom left). You can inspect and step through the entire process. The only info you need is that seal refers to NaCl's sealed box.

If this isn't free, then it's just a scam imo.

No, it's free.

This is a working code for python.

import base64
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_v1_5
import datetime
import struct
import requests

from Cryptodome.PublicKey import RSA

def main():
    print(encpass())

def encpass():
    password = "TESTPASSWORD"
    publickeyid, publickey = get_publickey_details("", "")
    session_key = get_random_bytes(32)
    iv = bytearray(12)
    time = str(int(datetime.datetime.now().timestamp()))
    decoded_publickey = base64.b64decode(publickey.encode())
    recipient_key = RSA.import_key(decoded_publickey)
    cipher_rsa = PKCS1_v1_5.new(recipient_key)
    enc_session_key = cipher_rsa.encrypt(session_key)
    cipher_aes = AES.new(session_key, AES.MODE_GCM, iv)
    cipher_aes.update(time.encode())
    ciphertext, tag = cipher_aes.encrypt_and_digest(password.encode("utf8"))
    payload = base64.b64encode((b"\x01\x00" + publickeyid.to_bytes(2, byteorder='big') + iv + len(enc_session_key).to_bytes(2, byteorder='big') + enc_session_key + tag + ciphertext))
    return f"#PWD_INSTAGRAM:4:{time}:{payload.decode()}"

def get_publickey_details(publickeyid, publickey):
    r = requests.get('https://i.instagram.com/api/v1/qe/sync/')
    publickeyid = int(r.headers['ig-set-password-encryption-key-id'])
    publickey = r.headers['ig-set-password-encryption-pub-key']
    return (publickeyid, publickey)


if __name__ == '__main__':
    main()

You can easily modify it to your code

Example Request

signed_body=SIGNATURE.{"jazoest":"","country_codes":"","phone_id":"","enc_password":":","username":"","adid":"","guid":"","device_id":"","google_tokens":"[]","login_attempt_count":""}

Example Response

{"logged_in_user": {"pk": , "username": "", "full_name": "", "is_private": , "profile_pic_url": "", "profile_pic_id": "", "is_verified": , "has_anonymous_profile_picture": , "can_boost_post": , "is_business": , "account_type": , "professional_conversion_suggested_account_type": , "is_call_to_action_enabled": , "can_see_organic_insights": , "show_insights_terms": , "total_igtv_videos": , "reel_auto_archive": "", "has_placed_orders": , "allowed_commenter_type": "", "nametag": , "is_using_unified_inbox_for_direct": , "interop_messaging_user_fbid": , "can_see_primary_country_in_settings": , "allow_contacts_sync": , "phone_number": ""}, "status": ""}

ValueError: RSA key format is not supported

always public_key get this issue ...

publickey: 201be917163e27f47c3837a08bfbc7497f78529b84425c1af4310ab62bca641b
key_id: 81
version: 10
time: 1596802463

ValueError: RSA key format is not supported

always public_key get this issue ...

publickey: 201be917163e27f47c3837a08bfbc7497f78529b84425c1af4310ab62bca641b

key_id: 81

version: 10

time: 1596802463

You used web, it's app

about signature key i know bro :( but i cant reg, its problem that i say

Same for me: {"message": "There was an error with your request. Please try again.", "status": "fail"}

Hi, am trying to solve a challenge where I need to submit a new password (mobile app) however, the mobile app for this challenge uses browser password_enc

enc_new_password1:

PWD_INSTAGRAM_BROWSER:10:1601582265:AWlQAMRz3yFgMTF+36wFijGbYcmskpslmjowJgbHDqdrm0d4WAy6qNU+9FPcXIeOL6Lc8fxUbNTa7kOzxV+RfzU0qBKBiCCQ4/nrUskI81cvkXYxSMlkNGtxHEblyMbWl3230ZnCJ///J06GwA==

enc_new_password2:

PWD_INSTAGRAM_BROWSER:10:1601582265:AWlQAFCtI4+6IjwDQBqD5CrLlBK/CG6IGXmOrDOP+9t0DRsPMpeYA3FLRR1QvrlMoy4X9Cy0B1JiiqBpinWTPIxmtACONPy4CjNNPQOTi+MwSLkaoj6KrmOTcUWdWoo74dNCycTbn6rL6vNyKA==

Passwords are both the same, but the two post params are different, I tried the #PWD_INSTAGRAM_BROWSER:0 trick to no avail.

Don't suppose anyone has any pointers on how about going about this. If was the website, could look at the JS files, but as this is coming from the phone app am at a loss

Guys, does anyone have a js code for registering api insta 4 version?

I read through this entire thread, and cannot find a working solution for nodejs enc_password. My code returns: { user: false, authenticated: false, status: 'ok' }

Folks, I don't know if it can be useful for someone, but I developed a new encryption function in Python that generate the enc_password.

Old versions in this thread uses RSA PubKey encryption, instead the new one uses the combination of AES-GCM/SealedBox from libsodium.

Gist Code: https://gist.github.com/lorenzodifuccia/c857afa47ede66db852e6a25c0a1a027

Folks, I don't know if it can be useful for someone, but I developed a new encryption function in Python that generate the enc_password.

Old versions in this thread uses RSA PubKey encryption, instead the new one uses the combination of AES-GCM/SealedBox from libsodium.

Gist Code: https://gist.github.com/lorenzodifuccia/c857afa47ede66db852e6a25c0a1a027

I'm not good with python. Is there anyway I can easily replicate this in JavaScript (node.js)?

Folks, I don't know if it can be useful for someone, but I developed a new encryption function in Python that generate the enc_password.
Old versions in this thread uses RSA PubKey encryption, instead the new one uses the combination of AES-GCM/SealedBox from libsodium.
Gist Code: https://gist.github.com/lorenzodifuccia/c857afa47ede66db852e6a25c0a1a027

I'm not good with python. Is there anyway I can easily replicate this in JavaScript (node.js)?

The JavaScript code posted somewhere here in this thread it's pretty ok, it just need some patches that I'll show below:
Link: https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js

  1. Install requirements for NodeJS: npm i node-webcrypto-ossl tweetnacl tweetnacl-sealedbox-js
  2. Download the JS script: wget https://github.com/unoemon/instagram-enc_passowrd-generator/blob/master/enc_passowrd-generator.js
  3. Patch the JS script: patch enc_passowrd-generator.js diff_patch.txt
  4. Run patched JS script: node enc_passowrd-generator.js

Here is the content of diff_patch.txt:

1,2c1
< const WebCrypto = require("node-webcrypto-ossl");
< const webcrypto = new WebCrypto();
---
> const webcrypto = new (require("node-webcrypto-ossl")).Crypto();
6,10c5,9
< exports.handler = async (event) => {
<   const APP_ID = '6';
<   const KEY_ID = '191';
<   const PUBLIC_KEY = '47c741b21d867bf5909ec70f86da86b9adcdff119c365f44f19d2f222f60260b';
<   const PASSWORD = 'passwrod123';
---
> generatePassword = async (appId, keyId, pubKey, password) => {
>   const APP_ID = appId;
>   const KEY_ID = keyId;
>   const PUBLIC_KEY = pubKey;
>   const PASSWORD = password;
32c31
<   return "#PWD_INSTAGRAM_BROWSER" + ':' + app_id + ':' + time + ':' + enc_password
---
>   return encodeURIComponent("#PWD_INSTAGRAM_BROWSER" + ':' + app_id + ':' + time + ':' + enc_password)
96,99c95
<   var t, o = [], c = str.length;
<   for (t = 0; t < c; t++)
<     o.push(String.fromCharCode(str[t]));
<   return btoa(o.join(''))
---
>   return Buffer.from(str, "binary").toString("base64");
107a104,106
> 
> // MAIN
> generatePassword("10", 72, "b3a328ff28b785092af6a578767877514c93a690a11b9d92ba0ce614c9d5db57", "CHANGE_PASSWORD_HERE")

Old versions in this thread uses RSA PubKey encryption, instead the new one uses the combination of AES-GCM/SealedBox from libsodium.

There are two versions of instagram you just mixed up. There's the web version AND the android version. They don't share the same api. So there's no old/new, there are just two different platforms.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ambross picture ambross  ·  10Comments

350d picture 350d  ·  53Comments

dhillon2325 picture dhillon2325  ·  14Comments

iMrDJAi picture iMrDJAi  ·  34Comments

MMrR0b0TT picture MMrR0b0TT  ·  18Comments