• crypter et décrypter des données avec AES et RSA

      Afin d’échanger des données depuis une API, sans que celles-ci ne soient interceptées par une tiers personne, il existe les cryptages symétriques et asymétriques.

      Symétrique : Même clé utilisée pour l’encryptage et le décryptage.

      Asymétrique : clés différentes. Il y aura une clé publique et une clé privée. Max 245 octets de données cryptées.

       

      Donc, il faudra :

      1 - Générer une clé aléatoire de 256 bits K.

      2 - Crypter les données avec un algorithme AES avec K.

      3 - Crypter la clé K avec RSA.

      4 - Envoyer le tout.

       

      P.S. Il y a du code python et Javascript au format byte. Le code fonctionnera mieux en 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 pour Python : pycryptodome

      PYTHON : décrypter la clé AES avec un algo RSA

      sudo pip3 install pycryptodome

       

      from Crypto.Cipher import PKCS1_OAEP
      from Crypto.PublicKey import RSA
      from base64 import b64encode
      from base64 import b64decode
      
      message = b'ma super phrase'
      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)

       

      Encrypted Text RWyFlzgncg/RtXrbrkjfPVSnpgq8ixuY8C7lcpkZYcu4Q40+VxuTkuKEQ5b4ofRpyn9QqOR0CiZPdGS66X1jReHE0KF6WxCHPkraa
      W04/26mvKOTEJSmZtW5hr77GJNAjWEnxGI4+70nCSKXjpVa07XUP51lIZllks7yu3KWdhg=
      Decrypted text b'ma super phrase'

      PYTHON : code pour l’algo AES

      Maintenant, on peut utiliser la clé précédemment crée pour décrypter les données

      import base64
      from Crypto.Cipher import AES
      from Crypto.Util.Padding import pad,unpad
      #AES ECB mode without IV
      data = '''{text: "ma super phrase",value:"toto"}'''
      key = 'AAAAAAAAAAAAAAAA' # 16 caractères pour 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"))

       

      encrypted ECB Base64: zLuiH8Jl9XroZb/vpSYc5kDd6WZIFClBcWLx9pIt3/SFOoQGlGjdrtwHd7mRHLkC
      decrypted data:  {text: "ma super phrase",value:"toto"}

      PYTHON : code pour générer une clé publique

      from Crypto.PublicKey import RSA
      
      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...

      JAVASCRIPT : algo RSA et création de la clé privée

      const crypto = require("crypto");
      
      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;
      }
      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");
      }
      
      let res = generateKeyFiles(); // Generate keys
      const plainText = "Mon super texte."; // Defining a text to be encrypted
      const encrypted = encryptString(plainText, res.publicKey); // Defining encrypted text
      console.log("Plaintext: ", plainText); // Prints plain text
      console.log("Encrypted: ", encrypted); // Prints encrypted text

      output:

      JAVASCRIPT : cryptage AES

      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:

       

      Voili voilou.

 

Aucun commentaire

 

Laissez un commentaire