Encrypt and Decrypt your data using AES and RSA algorithm (2024)

So few days back i got a task of implementing payload encryption for api calls for a application so that anyone trying to inspect/intercept api calls should not be able to understand payload and data that we are sending from from Frontend to Backend.

Sounds Interesting right….

Now a little basic there is two type of Encryption algorithm those are symmetric and asymmetric encryption .

Symmetric means same key used for both encryption and decryption.

Asymmetric means different key for encryption and decryption. Like there will be a Public key that will be shared to Front End and that is just needed for encryption only so if everyone have that key also we don’t even need to think of it. And there will be one Private key that only backend will have to decrypt that data, without private key u can’t retrieve raw data.

Now till if u have read u might think it’s easy just use asymmetric algo and convert data and done. But But there is a problem it can encrypt max 245 bytes like it’s kind of limited amount for bigger amount of data u can’t use this algo directly.

Now the Idea is to use one hack

  1. Generate a 256-bit random keystring K.
  2. Encrypt your data with AES algo with K.
  3. Encrypt K with RSA.
  4. Send both to the other side.

Now done, data is encrypted and anyone can’t decrypt also.In backend they can first decrypt keystring using RSA algoritm and using that keystring they can decrypt encrypted payload using AES algorithm. Here for demo i will use AES algorithm as symmetric algorithm, RSA algorithm as asymmetric algorithm. Don’t worry this are most widely used algoritm in industry.

P.S. I will provide code for python and Javascript both as python mostly do things in byte format so my code will make your work easier to convert those bytes to string and u can share key,encrypted data everything among python and javascript codebase it will make your life easier if you have backend in python and front end in Javascript.

pakcage used : pycryptodome(python)

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from base64 import b64encode
from base64 import b64decode
# working
message = b'AAAAAAAAAAAAAAAA'
key = RSA.importKey('''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTTmFGImcfELsAJIr27eiAMJMn
pCJH9YeAC71XJAbP2OzVulKEeo43ILknTM8efCT0HwoG+tLY9XMe4a+zM7FhYZJx
mQYsur3jxgRvCEWEN0pvgv3BVdE9APxg9gXvTJGjDAqFnOO0aS4+wywGJmx+lFxL
Fa4IDlf/jCIv2+NqmwIDAQAB
-----END PUBLIC KEY-----''')
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(message)
print("Encrypted Text", b64encode(ciphertext).decode('utf-8'))
encodedText=b64encode(ciphertext).decode('utf-8')
ct = b64decode(encodedText)

ciphertext=ct
key = RSA.importKey('''-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANNOYUYiZx8QuwAk
ivbt6IAwkyekIkf1h4ALvVckBs/Y7NW6UoR6jjcguSdMzx58JPQfCgb60tj1cx7h
r7MzsWFhknGZBiy6vePGBG8IRYQ3Sm+C/cFV0T0A/GD2Be9MkaMMCoWc47RpLj7D
LAYmbH6UXEsVrggOV/+MIi/b42qbAgMBAAECgYEAn05LVfXf6vLRGQVz40Bv9h0p
BEzhL4Ezm9y97bGSlSbFP0kOpyRCjdtU3AUzbZdIwOeZxrNZPQqntROPRDpnslV2
EdIctBKbO1jKlR3jurbUv/pHdcQqNkxnYLtjENjJS7+ikEIH1HBfsWGxXZgs38b4
OPY3L0ezZmN/Kyf7E2ECQQDtx025LkNS5R+j7zYG2qxa9kQXaQ1QetYXxSKKH6ZA
iSoUFxD8mA7zUQS8lwLLfMcGT2lMAkUrw89YbXmOmdNLAkEA43+/FS578fOAaLQf
GiCjtrc7E+rLY+PeRKFQQv/3sSChQMmLiNbtEb28gMB8x67dGALh7jqhpza+frY8
uSjj8QJADNf7JsmM8WlW8C/3px8guDkdLHaMNZCtB9OqLfPPsyS1lSg5zqsYA6SY
sOcnS36N8ZVQhr6IpfiJtqkTK9S7SQJAKON18ZWoO0Vbp/XvvR9urVFjceH6alqz
QTyJE3G0EAbgVKekx5RxiYXDkpSGGNGp9T3XY5zwHwCs3lNcuJ7L0QJARjziBEhy
mqkA8eNSZkY85hDIpphu39BWPYjcgtc+h8FBw6hRhPM1oa2sonQ912WYt1XPRlll
oehB38cpwcx3Og==
-----END PRIVATE KEY-----''')

cipher = PKCS1_OAEP.new(key)
message = cipher.decrypt(ciphertext)
print("Decrypted text",message)

output:

Encrypt and Decrypt your data using AES and RSA algorithm (2)

we can use that key we got from previous algorithm here to decrypt payload data kept it harcoded here to make 2 files independent

import base64 
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad

#AES ECB mode without IV

data = '''{text: "I love Medium",value:"some"}'''
key = 'AAAAAAAAAAAAAAAA' #Must Be 16 char for AES128

def encrypt(raw):
raw = pad(raw.encode(),16)
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
return base64.b64encode(cipher.encrypt(raw))

def decrypt(enc):
enc = base64.b64decode(enc)
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
return unpad(cipher.decrypt(enc),16)

encrypted = encrypt(data)
print('encrypted ECB Base64:',encrypted.decode("utf-8", "ignore"))
encrypted=encrypted.decode("utf-8", "ignore")
decrypted = decrypt(encrypted)
print('decrypted data: ',decrypted.decode("utf-8", "ignore"))

output:

Encrypt and Decrypt your data using AES and RSA algorithm (3)
def createPublicPrivateKey():
# Generate RSA key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)

# Get public key
public_key = private_key.public_key()

# Serialize keys to PEM format
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)

public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# Convert bytes to string
private_key_str = private_key_pem.decode('utf-8')
public_key_str = public_key_pem.decode('utf-8')

return {
"publicKey":public_key_str,
"privateKey":private_key_str

}

Done From Python Side….

Now to Implement this same thing in Javascript here you go.

const crypto = require("crypto");

// working
// Using a function generateKeyFiles
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync("rsa", {
modulusLength: 1024,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});

// Creating public key file
console.log(keyPair.privateKey);
console.log(keyPair.publicKey);
return keyPair;
}

// Creating a function to encrypt string
function encryptString(plaintext, publicKey) {
// const publicKey = fs.readFileSync(publicKeyFile, "utf8");

// publicEncrypt() method with its parameters
const encrypted = crypto.publicEncrypt(
{ key: publicKey },
Buffer.from(plaintext)
);
return encrypted.toString("base64");
}

// Generate keys
let res = generateKeyFiles();

// Defining a text to be encrypted
const plainText = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";

// Defining encrypted text
const encrypted = encryptString(plainText, res.publicKey);

// Prints plain text
console.log("Plaintext:", plainText);

// Prints encrypted text
console.log("Encrypted: ", encrypted);

output:

Encrypt and Decrypt your data using AES and RSA algorithm (4)
const CryptoJS = require("crypto-js");

const secretKey = "AAAAAAAAAAAAAAAA";
const dataToEncrypt = "{id:'abcfasf asf a',value:'xyz'}";

var keyHex = CryptoJS.enc.Utf8.parse(secretKey);
const encryptedData = CryptoJS.AES.encrypt(dataToEncrypt, keyHex, {
mode: CryptoJS.mode.ECB,
});
console.log("Encrypted Data:", encryptedData.toString());

output:

Encrypt and Decrypt your data using AES and RSA algorithm (5)

Now you can play around with this code by pasting encrypted data directly into codebase and decrypting them .

That’s it . Peace out ✌️

Encrypt and Decrypt your data using AES and RSA algorithm (2024)
Top Articles
How to Change NAT Status | Help Center l Mystnodes.com
How to deal with toxic people: 9 powerful tips
Condogames Xyz Discord
Christine Paduch Howell Nj
K-Active – Jetzt kaufen bei SVG
wat is het? Beschrijving met kenmerken. Kenmerken voering puhoderzhaschey materiaal. Taffett wordt nat?
Ap Spanish Score Calculator
The Exorcist: Believer Showtimes Near Movie Tavern Brannon Crossing
Grifolsplasma.com Donor-Portal
Fuego Azteca Mexican Bar And Grill Live Oak Photos
Trisha Paytas Botched Boob Job
Is it worth doing financial modelling?
Lulu's Leis And Bouquets
Sounder Mariners Schedule
Craigslist Ludington Michigan
Plarium Trick Or Treat
2068032104
Understanding The Payment Structure Behind Online Slot Machines
Quiktrip Maple And West
Centricity Time And Attendance Premier Health
Journal and Courier from Lafayette, Indiana
Hillside Funeral Home Washington Nc Obituaries
Gabrielle Abbate Obituary
Lucki White House Lyrics
Gas Station Near Santa Barbara Airport
Maps Michigan Login
Weekly Math Review Q4 4 Answer Key | airSlate SignNow
The Ben Shapiro Show Soundcloud
7 Lovely Ways To Say I Love You In Thai - ling-app.com
80 For Brady Showtimes Near Regal Largo Mall
Florida surgeon general favorably recommended after Democrats walk out of confirmation hearing | CNN Politics
Kathy Vold From Heartland
Backoffice.paperpie
Craiglist Sacramento Ca
They're Cast In Some Shows Crossword Clue
Week 2 NFL Power Rankings: 1-32 poll, plus which newcomer had the best performance for every team?
Metro 72 Hour Extension 2022
Log into the Parent Portal and the Parent App
Portugal Anúncios Classificados OLX
Gander Rv Hamburg Ny
Dr. Rolando Lozano Md Elizabeth Nj
Blackstone Launchpad Ucf
Hobby Lobby Pelican
MERRY AND MARRIED MERRY & MARRIED MERRY + MARRIED MERRY E MARRIED MERRY ; MARRIED MERRY, MARRIED MERRY - MARRIED Trademark Application of Nexus Integrity Group - Serial Number 98485054 :: Justia Trademarks
Apartments / Housing For Rent near Brooksville, FL - craigslist
Violent Night Showtimes Near The Grand 16 - Lafayette
1V1 Google Classroom
First Mess Blog
Cl Bellingham
Craigslist Org St George
Shaw University Football Roster
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6085

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.