Skip to content

Instantly share code, notes, and snippets.

@mumayank
Last active December 11, 2018 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mumayank/15968b8859dcd64d9245005abc1c9c61 to your computer and use it in GitHub Desktop.
Save mumayank/15968b8859dcd64d9245005abc1c9c61 to your computer and use it in GitHub Desktop.
public class ServerDecrypt {
static String privateKey = "<your_private_key_here>";
static String encryptedTextString = "<your_received_encrypted_text_here>";
static String encryptedSecretKeyString = "<your_received_encrypted_secret_key_here>";
public static void main(String args[]) {
try {
// 1. Get private key
PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey, Base64.DEFAULT));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(privateSpec);
// 2. Decrypt encrypted secret key using private key
Cipher cipher1 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
byte[] secretKeyBytes = cipher1.doFinal(Base64.decode(encryptedSecretKeyString, Base64.DEFAULT));
SecretKey secretKey = new SecretKeySpec(secretKeyBytes, 0, secretKeyBytes.length, "AES");
// 3. Decrypt encrypted text using secret key
byte[] raw = secretKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] original = cipher.doFinal(Base64.decode(encryptedTextString, Base64.DEFAULT));
String text = new String(original, Charset.forName("UTF-8"));
// 4. Print the original text sent by client
System.out.println("text\n" + text + "\n\n");
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment