Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 24, 2018 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/0357be17d3bbd9bd3820631cacc3e188 to your computer and use it in GitHub Desktop.
Save parzibyte/0357be17d3bbd9bd3820631cacc3e188 to your computer and use it in GitHub Desktop.
Acortar links y crear pastes con la API de binbox.io
"""
API de Binbox escrita en Python
Requisitos:
* requests
* sjcl
Para instalar requests:
pip install requests
Para instalar sjcl (Stanford Javascript Crypto Library) ir a https://github.com/berlincode/sjcl/blob/master/sjcl/sjcl.py
descargar el fichero en la carpeta en donde esté este archivo, y en la línea 170 cambiar:
ciphertext = cipher.encrypt(plaintext)
Por:
ciphertext = cipher.encrypt(plaintext.encode("utf-8"))
"""
import requests
import json
import string
import random
from sjcl import SJCL
from base64 import b64encode
class BB:
def __init__(self, nombre_de_usuario):
self.url_api = "http://{}.binbox.io/submit.json".format(nombre_de_usuario)
def obtener_link_o_lanzar_error(self, peticion, sal = None):
respuesta_decodificada = json.loads(peticion.text)
if respuesta_decodificada['ok'] is True:
link = "https://binbox.io/{}".format(respuesta_decodificada['id'])
if sal is not None:
link += "#{}".format(sal)
return link
else:
raise ValueError("Link o usuario inválido. Mensaje original: {}".format(peticion.text))
def cadena_aleatoria(self, longitud = 8):
"""
Devuelve una cadena aleatoria de 8 caracteres para ser utilizada como sal.
Nota: esto no es seguro criptográficamente, pero sí aleatoriamente
Nota 2: no intentes cambiar la longitud
"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=longitud))
def acortar_link(self, link, titulo = None):
"""
Devuelve un link acortado
Por ejemplo, algo como binbox.io/asdf
"""
datos = {
'url': link,
'title': titulo
}
peticion = requests.post(self.url_api, data = datos)
return self.obtener_link_o_lanzar_error(peticion)
def crear_paste(self, titulo, texto, sal = None):
"""
Devuelve el link del paste, con su respectivo hash e id.
Por ejemplo, algo como http://binbox.io/asdf#asdw
Para el título puedes incluir links como https://ejemplo.com pero
no HTML como <a href="https://ejemplo.com">Link</a>
Y para saltos de línea utiliza \n, no intentes utilizar <br>
"""
if sal is None:
sal = self.cadena_aleatoria()
texto_encriptado = SJCL().encrypt(texto, sal)
texto_encriptado['ct'] = texto_encriptado['ct'].decode('utf-8')
texto_encriptado['iv'] = texto_encriptado['iv'].decode('utf-8')
texto_encriptado['salt'] = texto_encriptado['salt'].decode('utf-8')
texto_encriptado_como_json = json.dumps(texto_encriptado, separators=(',', ':'))
texto_como_json_codificado = b64encode(texto_encriptado_como_json.encode('utf-8'))
texto_base64_decodificado = texto_como_json_codificado.decode('utf-8')
datos = {
'data': texto_base64_decodificado,
'title': titulo,
}
peticion = requests.post(self.url_api, data = datos)
return self.obtener_link_o_lanzar_error(peticion, sal)
""" Ejemplos """
binbox = BB("parzibyte")
link_paste = binbox.crear_paste("El título del paste", "El contenido que puede\nllevar saltos de\nlínea y también https://parzibyte.me/ enlaces")
link_acortado = binbox.acortar_link("https://parzibyte.me/", "Este es el título del link")
print(link_paste)
print(link_acortado)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment