Skip to content

Instantly share code, notes, and snippets.

@lorenzodifuccia
Created December 22, 2020 02:12
Show Gist options
  • Save lorenzodifuccia/c857afa47ede66db852e6a25c0a1a027 to your computer and use it in GitHub Desktop.
Save lorenzodifuccia/c857afa47ede66db852e6a25c0a1a027 to your computer and use it in GitHub Desktop.
Encryption function used by Instagram (Browser App) to generate the 'enc_password' from PubKey (AES-GCM + SealedBox)
import base64
import struct
import datetime
import binascii
from urllib.parse import quote_plus
# pip install pycryptodomex
from Cryptodome import Random
from Cryptodome.Cipher import AES
# pip install PyNaCl
from nacl.public import PublicKey, SealedBox
def encrypt_password(key_id, pub_key, password, version=10):
key = Random.get_random_bytes(32)
iv = bytes([0] * 12)
time = int(datetime.datetime.now().timestamp())
aes = AES.new(key, AES.MODE_GCM, nonce=iv, mac_len=16)
aes.update(str(time).encode('utf-8'))
encrypted_password, cipher_tag = aes.encrypt_and_digest(password.encode('utf-8'))
pub_key_bytes = binascii.unhexlify(pub_key)
seal_box = SealedBox(PublicKey(pub_key_bytes))
encrypted_key = seal_box.encrypt(key)
encrypted = bytes([1,
key_id,
*list(struct.pack('<h', len(encrypted_key))),
*list(encrypted_key),
*list(cipher_tag),
*list(encrypted_password)])
encrypted = base64.b64encode(encrypted).decode('utf-8')
return quote_plus(f'#PWD_INSTAGRAM_BROWSER:{version}:{time}:{encrypted}')
print(encrypt_password(72, "b3a328ff28b785092af6a578767877514c93a690a11b9d92ba0ce614c9d5db57", "CHANGE_PASSWORD_HERE"))
@godxgamer
Copy link

yep this not working i changed the keys still getting this error

@tabekg
Copy link

tabekg commented Jun 6, 2024

any solution for this issue?

@tabekg
Copy link

tabekg commented Jun 6, 2024

yep this not working i changed the keys still getting this error

In my case, I encrypt with version 10, but version is 9. You should get actual version from https://www.instagram.com/data/shared_data/ -> encryption.version

@mobeigi
Copy link

mobeigi commented Aug 21, 2024

Thank you for sharing this!

I am using it in the fb2cal project to properly authenticate: https://github.com/mobeigi/fb2cal/blob/master/fb2cal/utils.py#L22-L50

I was using plain text password before which seems to have only recently stopped working.
Made minor change for header and version to support Facebook Web instead of Instagram.

Question for @tabekg , are you aware of any Facebook Web equivalent to: https://www.instagram.com/data/shared_data/
I'd like to programmatically get the version too for Facebook Web rather than hard coding it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment