0

Hey I need to encrypt a message in python but I have a javascript example.

This is what I have.

BLOCK_SIZE=16
message = 1234
passphrase = "ed8b1a3b-5cf1-4ba5-87af-790905f6bae3"
def encrypt(message, passphrase):
    # passphrase MUST be 16, 24 or 32 bytes long, how can I do that ?
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_ECB, IV)
    return base64.b64encode(aes.encrypt(message))

print (encrypt(message , passphrase))

and here is the example

import * as CryptoJS from 'crypto-js';

  aesEncrypt(text, key){
    let k = key.replace(/-/g, '').substring(0,16);
    k = CryptoJS.enc.Utf8.parse(k);
    const iv = CryptoJS.enc.Utf8.parse('0000000000000000');
    const encrypted = CryptoJS.AES.encrypt(text.trim(), k, {
      keySize: 16,
      iv: iv,
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    console.log(encrypted.toString());
    return encrypted.toString();
  }

1 Answers1

0
  1. always read the docs and check for similar questions prior to posting. Here is a link to a similar post as well as how to do this in a simple way directly from the docs. hope it helps.

install The Crypo Lib

pip install cryptography

Then Use The following

>>> from cryptography.fernet import Fernet
>>> # Put this somewhere safe!
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> token = f.encrypt(b"A really secret message. Not for prying eyes.")
>>> f.decrypt(token)

Example Output 'A really secret message. Not for prying eyes.'

from cryptography.fernet import Fernet

message = "A really secret message. Not for prying eyes."
key = Fernet.generate_key()

def encrypt(message, key):
        f = Fernet(key)
        token = f.encrypt(b"A really secret message. Not for prying eyes.")
        print(token)
        decrypted = f.decrypt(token)
        print(decrypted)


encrypt(message, key)

Links -Doc Lib https://pypi.org/project/cryptography/

Similar Question On Stackoverflow with more verbose answers than mine above,

How do I encrypt and decrypt a string in python?

Josh
  • 1,059
  • 10
  • 17