Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Cómo escribir el equivalente de esta función de cifrado de Java en Node JS

Esta es la función utilizada para cifrar en Java

 public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new BufferedReader(new FileReader(pemFileLocation)); String line; while ((line = br.readLine()) != null) { strKeyPEM += line + "\n"; } br.close(); String publicKeyPEM = strKeyPEM; System.out.println(publicKeyPEM); publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", ""); publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");; byte[] encoded = Base64.getDecoder().decode(publicKeyPEM); // byte[] encoded = Base64.decode(publicKeyPEM); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded)); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherData = cipher.doFinal(fieldValue.getBytes()); if (cipherData == null) { return null; } int len = cipherData.length; String str = ""; for (int i = 0; i < len; i++) { if ((cipherData[i] & 0xFF) < 16) { str = str + "0" + java.lang.Integer.toHexString(cipherData[i] & 0xFF); } else { str = str + java.lang.Integer.toHexString(cipherData[i] & 0xFF); } } return str.trim(); } catch (Exception e) { System.out.println("oops2"); System.out.println(e); } return null; }

Quiero el equivalente de esto en javascript/Nodejs, probé esto:

 import * as NodeRSA from 'node-rsa'; private encryptionFunction(fieldValue: string , pemkey: string) : string { const rsa = new NodeRSA(pemkey); const encrypted= rsa.encrypt(fieldValue , 'hex') return encrypted }

Pero el tamaño de salida de ambas funciones es el mismo, pero aparentemente el tipo de cifrado es incorrecto.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Node-RSA aplica OAEP ( aquí ) como relleno de forma predeterminada, por lo que el relleno PKCS#1 v1.5 utilizado en el código Java debe especificarse explícitamente. Esto debe agregarse después de importar la clave y antes del cifrado:

 rsa.setOptions({ encryptionScheme: 'pkcs1' });

Alternativamente, el relleno se puede especificar directamente durante la importación de claves:

 const rsa = new NodeRSA(pemkey, { encryptionScheme: 'pkcs1' });

Con este cambio, ambos códigos son funcionalmente idénticos.


Con respecto a las pruebas: tenga en cuenta que el cifrado RSA no es determinista, es decir, dada la misma entrada (clave, texto sin formato), cada cifrado proporciona un texto cifrado diferente . Por lo tanto, los textos cifrados de ambos códigos (funcionalmente idénticos) serán diferentes incluso si la entrada es idéntica. Entonces esto no es un error, sino el comportamiento esperado.
¿Cómo se puede probar entonces la equivalencia de ambos códigos? Por ejemplo, descifrando ambos textos cifrados con el mismo código/herramienta.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!