'Encrypting using node-forge package with angular (typescript) and decrypting using python cryptography module

I am using an angular service like the following to encrypt data in my web app:

import { Injectable } from '@angular/core';
import * as forge from 'node-forge';

@Injectable({
  providedIn: 'root',
})
export class RSAHelper {
  publicKey: string = ...;

  constructor() {}

  encrypt(data: string): string {
    const rsa = forge.pki.publicKeyFromPem(this.publicKey);
    return forge.util.encode64(rsa.encrypt(data, 'RSA-OAEP', {
      md: forge.md.sha256.create(),
      mgf1: {
        md: forge.md.sha256.create()
      }
    }));
  }
}

In my python API server, I'm decrypting it using a module like the following:

import pickle

import base64

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding


def get_private_key(filename):
    with open(filename, "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )

    return private_key


def decrypt(private_key, encrypted_message):
    encrypted_message = base64.b64decode(encrypted_message)

    bytes_message = private_key.decrypt(
        encrypted_message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )

    return pickle.loads(bytes_message)

The API server gives the error:

line ..., in decrypt
api          |     return pickle.loads(bytes_message)
api          | _pickle.UnpicklingError: could not find MARK

The data I'm encrypting/decrypting is a string. The keys are well generated. When doing encryption/decryption only from python it works. When doing encryption/decryption only from typescript, it also works. I can't figure out the problem.



Solution 1:[1]

You'll probably also want to consider capitalization.

Should Milk be added if milk is there? If not, make sure you're comparing lowercase to lowercase.

new_item = "milk"
for l in shopping_cart:
    l_lc = [x.lower() for x in l] # lowercase version of list
    if new_item.lower() not in l_lc:
        l.append(new_item)

You could also consider having a "shadow" dictionary so you're doing faster lookups and not converting the list to lowercase every time. Replace each list with a structure that has the list, as well as a dictionary of each item in lower case. May be overkill if it's a small list of lists.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user984003