I have a backend in java-spring boot. I implemented RSA in Java in API call, such that every API request should be done with encrypted data and response should be decrypted . The java code is as:
public static String encrypt(String strToEncrypt){
try {
byte[] keyBytes = Files.readAllBytes(Paths.get(PUBLIC_KEY_FILE));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] strBytes = strToEncrypt.getBytes("UTF-8");
int inputLength = strBytes.length;
int offset = 0;
int maxBlockSize = 245;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while (inputLength - offset > 0) {
byte[] block;
if (inputLength - offset > maxBlockSize) {
block = cipher.doFinal(strBytes, offset, maxBlockSize);
} else {
block = cipher.doFinal(strBytes, offset, inputLength - offset);
}
outputStream.write(block, 0, block.length);
offset += maxBlockSize;
}
byte[] encryptedBytes = outputStream.toByteArray();
return Base64.getEncoder().encodeToString(encryptedBytes) + SUFFIX;
} catch (Exception e) {
System.out.println("Error encrypting string: " + e.getMessage());
return strToEncrypt;
}
}
public static String decrypt(String strToDecrypt) {
try {
if (strToDecrypt == null || strToDecrypt.isEmpty() || !strToDecrypt.endsWith(SUFFIX)) {
return strToDecrypt;
}
strToDecrypt = strToDecrypt.replace(SUFFIX, "");
byte[] keyBytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] encryptedBytes = Base64.getDecoder().decode(strToDecrypt);
int inputLength = encryptedBytes.length;
int offset = 0;
int maxBlockSize = 256;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while (inputLength - offset > 0) {
byte[] block;
if (inputLength - offset > maxBlockSize) {
block = cipher.doFinal(encryptedBytes, offset, maxBlockSize);
} else {
block = cipher.doFinal(encryptedBytes, offset, inputLength - offset);
}
outputStream.write(block, 0, block.length);
offset += maxBlockSize;
}
byte[] decryptedBytes = outputStream.toByteArray();
return new String(decryptedBytes, "UTF-8");
} catch (Exception e) {
System.out.println("Error decrypting string: " + e.getMessage());
return strToDecrypt;
}
}
`
How do I implement this in react? I have a two set of Key-Pair , How should i do it ? Is there any way to do with single pair of keys ? . Please explain and provide the react-js code.