Last active
June 18, 2020 11:26
-
-
Save uttesh/9a4f9cb73709aa7fffc1264881c57d1c to your computer and use it in GitHub Desktop.
Encrypt the data in the NodeJS application and decrypt in the Java application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let crypto = require("crypto"); | |
let text = "the big brown fox jumped over the fence"; | |
function encrypt(text) { | |
let cipher = crypto.createCipher("aes-128-ecb", "somepassword"); | |
let crypted = cipher.update(text, "utf-8", "hex"); | |
crypted += cipher.final("hex"); | |
return crypted.toString(); | |
} | |
function decrypt(encryptedText) { | |
let decipher = crypto.createDecipher("aes-128-ecb", "somepassword"); | |
let decrypted = decipher.update(encryptedText, "hex", "utf8"); | |
decrypted += decipher.final("utf-8"); | |
return decrypted.toString(); | |
} | |
let encData = encrypt(text); | |
console.log("crypted: ", encData); | |
console.log("decrypted: ", decrypt(encData)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.MessageDigest; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
public class SimpleDecrypt { | |
public static void main(String[] args) throws Exception { | |
String encData="67a0fd39e75e37bc0743147d43b9487bde7db1f5ef798da4e570d6595190dd682a9d4491b47ad26c94e11e1e464e8bb1"; | |
String decData = decrypt("somepassword", encData); | |
System.out.println("decData :: "+decData); | |
} | |
private static String decrypt(String seed, String encrypted) throws Exception { | |
byte[] keyb = seed.getBytes("UTF-8"); | |
MessageDigest md = MessageDigest.getInstance("MD5"); | |
byte[] thedigest = md.digest(keyb); | |
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES"); | |
Cipher dcipher = Cipher.getInstance("AES"); | |
dcipher.init(Cipher.DECRYPT_MODE, skey); | |
byte[] clearbyte = dcipher.doFinal(toByte(encrypted)); | |
return new String(clearbyte); | |
} | |
private static byte[] toByte(String hexString) { | |
int len = hexString.length()/2; | |
byte[] result = new byte[len]; | |
for (int i = 0; i < len; i++) { | |
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue(); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment