10

Cryptography App

A Basic Cryptography Program with python and Javascript

from flask import Flask, request, jsonify
from cryptography.fernet import Fernet
 
app = Flask(__name__)
# Generate a key for encrypting and decrypting
# Note: In a real app, you'd want to keep this key secure
key = Fernet.generate_key()
cipher_suite = Fernet(key)
 
@app.route('/encrypt', methods=['POST'])
def encrypt():
    data = request.json
    if 'message' in data:
        encrypted_message = cipher_suite.encrypt(data['message'].encode())
        return jsonify({'encrypted': encrypted_message.decode()})
    return jsonify({'error': 'Message is required'}), 400
 
@app.route('/decrypt', methods=['POST'])
def decrypt():
    data = request.json
    if 'message' in data:
        decrypted_message = cipher_suite.decrypt(data['message'].encode())
        return jsonify({'decrypted': decrypted_message.decode()})
    return jsonify({'error': 'Message is required'}), 400
 
if __name__ == '__main__':
    app.run(debug=True)
 
------------------
 
document.addEventListener("DOMContentLoaded", function() {
  // Get references to the DOM elements
  const encryptBtn = document.getElementById("encryptBtn");
  const decryptBtn = document.getElementById("decryptBtn");
  const inputMessage = document.getElementById("inputMessage");
  const outputMessage = document.getElementById("outputMessage");
 
  // Function to handle encryption
  encryptBtn.addEventListener("click", function() {
    const message = inputMessage.value;
    if (message) {
      fetch('/encrypt', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: message }),
      })
      .then(response => response.json())
      .then(data => {
        outputMessage.value = data.encrypted;
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    }
  });
 
  // Function to handle decryption
  decryptBtn.addEventListener("click", function() {
    const message = inputMessage.value;
    if (message) {
      fetch('/decrypt', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: message }),
      })
      .then(response => response.json())
      .then(data => {
        outputMessage.value = data.decrypted;
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    }
  });
});
 
MIT License
 
Copyright (c) 2024 KM Fazle
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: