Skip to content

Instantly share code, notes, and snippets.

@Cepr0
Created March 14, 2021 18:08
Show Gist options
  • Save Cepr0/867a643389b9d06c3b0f642dc3f52d6f to your computer and use it in GitHub Desktop.
Save Cepr0/867a643389b9d06c3b0f642dc3f52d6f to your computer and use it in GitHub Desktop.
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
@Component
public class RsaDecryptor implements Decryptor {
public static final String RSA = "RSA";
private final KeyPair keyPair;
public RsaDecryptor(KeyPair keyPair) {
this.keyPair = keyPair;
}
@Override
public InputStream decrypt(String encryptedText) {
try {
byte[] encryptedData = encryptedText.getBytes(ISO_8859_1);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
Cipher cipher = Cipher.getInstance(RsaDecryptor.RSA);
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] decryptedData = cipher.doFinal(decodedData);
return new ByteArrayInputStream(decryptedData);
} catch (Exception e) {
throw new DecryptionException("Couldn't decrypt the text: " + encryptedText + ", cause: " + e.toString(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment