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
United Parcel Service, Inc. (UPS) Stock Forecast & Price Targets - Stock Analysis
The Beginner's Guide to Lost Ark Chaos Dungeons
Forozdz
Bin Stores in Wisconsin
Free Atm For Emerald Card Near Me
Do you need a masters to work in private equity?
Strange World Showtimes Near Cmx Downtown At The Gardens 16
Craigslist Free Grand Rapids
Valentina Gonzalez Leak
Worcester On Craigslist
Saberhealth Time Track
Erica Banks Net Worth | Boyfriend
Cta Bus Tracker 77
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
Blue Rain Lubbock
Barber Gym Quantico Hours
U Of Arizona Phonebook
67-72 Chevy Truck Parts Craigslist
Gazette Obituary Colorado Springs
Two Babies One Fox Full Comic Pdf
Toothio Login
University Of Michigan Paging System
Makemv Splunk
Downloahub
Why comparing against exchange rates from Google is wrong
Craigslist Sf Garage Sales
Mercedes W204 Belt Diagram
Hoofdletters voor God in de NBV21 - Bijbelblog
15 Downer Way, Crosswicks, NJ 08515 - MLS NJBL2072416 - Coldwell Banker
Gerber Federal Credit
R Nba Fantasy
Kelley Blue Book Recalls
craigslist | michigan
Dr Adj Redist Cadv Prin Amex Charge
Ferguson Employee Pipeline
What Is A K 56 Pink Pill?
Sallisaw Bin Store
Yakini Q Sj Photos
Quick Base Dcps
Stosh's Kolaches Photos
3500 Orchard Place
Tropical Smoothie Address
Hughie Francis Foley – Marinermath
Erespassrider Ual
Muni Metro Schedule
Oak Hill, Blue Owl Lead Record Finastra Private Credit Loan
Research Tome Neltharus
Rocket Bot Royale Unblocked Games 66
Deviantart Rwby
Predator revo radial owners
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.