I receive the error "Ciphertext length must be equal to key size." when trying to send an encoded message from javascript to python. I have encoded the bytesarray to base64 in javascript and decoded the base64 back to a bytes array in Python. Yet, the issue seems to persist.
Key Generation (Python):
RSA_SECRET_KEY = rsa.generate_private_key(
public_exponent=65537,
key_size=4096
)
RSA_PUBLIC_KEY = RSA_SECRET_KEY.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
Import Key (Javascript):
async function importRsaKey(pem) {
// fetch the part of the PEM string between header and footer
const pemHeader = "-----BEGIN PUBLIC KEY-----";
const pemFooter = "-----END PUBLIC KEY-----";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length - 1);
// base64 decode the string to get the binary data
const binaryDerString = window.atob(pemContents);
// // convert from a binary string to an ArrayBuffer
const binaryDer = str2ab(binaryDerString);
var key = await crypto.subtle.importKey(
"spki",
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
true,
["encrypt"]
);
return key;
}
Encrypt Data (Javascript):
async function encrypt(key, msg) {
return await crypto.subtle.encrypt(
{name:"RSA-OAEP"},
key,
str2ab(msg)
)
}
Transmit Data (Javascript):
const handleSubmit = (e) => {
e.preventDefault();
const rsa_key_promise = importRsaKey(public_key);
rsa_key_promise
.then((rsa_key) =>
{
encrypt(rsa_key, "test")
.then((data) =>
{
axiosInstance
.post(`auth/token/`, {
hash: window.btoa(data),
})
... more code
Receive and decode data (Python):
def post(self, request, *args, **kwargs):
response = Response(status.HTTP_400_BAD_REQUEST)
try:
enc = base64.b64decode(request.data['hash'])
dec = settings. \
RSA_SECRET_KEY.decrypt(enc,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
except Exception as e:
print(e)
return response