Encrypt/Decryption RSA communication Java-PHP - java

I'm trying to implement a client-server communication encrypted with RSA.
I generate private and public key pairs in java then I pass some inputs to a PHP script through GET parameters. If there is only the key set as GET parameter the script encrypts a phrase that will be decrypted from the client (by java) otherwise if it's set a message (the m parameters see the PHP script) it should be able to decrypt it.
I coded the following:
java:
public static void main(String[] args) throws Exception {
// Generate public and private keys using RSA
Map<String, Object> keys = getRSAKeys();
PrivateKey privateKey = (PrivateKey) keys.get("private");
PublicKey publicKey = (PublicKey) keys.get("public");
StringBuilder keypublic = new StringBuilder();
keypublic.append("-----BEGIN PUBLIC KEY-----\n");
keypublic.append(Base64.getMimeEncoder().encodeToString(publicKey.getEncoded()) + "\n");
keypublic.append("-----END PUBLIC KEY-----\n");
StringBuilder keyprivate = new StringBuilder();
keypublic.append("-----BEGIN PRIVATE KEY-----\n");
keypublic.append(Base64.getMimeEncoder().encodeToString(privateKey.getEncoded()) + "\n");
keypublic.append("-----END PRIVATE KEY-----\n");
String keyEncodedPublic = Base64.getEncoder().encodeToString(keypublic.toString().getBytes());
String keyEncodedPrivate = Base64.getEncoder().encodeToString(keypublic.toString().getBytes());
String signature = sign("MyEncryptedInternalString", privateKey);
//Offuscare la MyEncryptedInternalString in qualche modo
System.out.println("key: \n" + Base64.getEncoder().encodeToString(signature.getBytes()) + ":" +
keyEncodedPublic);
System.out.println("\n");
System.out.println("Crypted: \n" + Base64.getEncoder().encodeToString(encryptMessage("hello", privateKey).getBytes()));
//System.out.println("Verified? " + verify("test",signature,publicKey));
while(true) {
Scanner out = new Scanner(System.in);
System.out.print("Insert text: ");
String enc = out.nextLine();
String descryptedText = decryptMessage(enc, privateKey);
System.out.println("Decrypted: " + descryptedText);
System.out.println();
}
}
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signature = privateSignature.sign();
return Base64.getEncoder().encodeToString(signature);
}
// Get RSA keys. Uses key size of 2048.
private static Map<String,Object> getRSAKeys() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
Map<String, Object> keys = new HashMap<String,Object>();
keys.put("private", privateKey);
keys.put("public", publicKey);
return keys;
}
// Decrypt using RSA public key
private static String decryptMessage(String encryptedText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)));
}
// Encrypt using RSA private key
private static String encryptMessage(String plainText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes()));
}
And the PHP script:
<?php
function RSAEncryptMessage($string, $key){
$data = "MyEncryptedInternalString";
$parts = explode(":",$key);
$signature = base64_decode($parts[0]);
$pubkeyid = $parts[1];
$ok = openssl_verify($data, base64_decode($signature), base64_decode($pubkeyid), "sha256WithRSAEncryption");
if ($ok == 1){
$pubkeyid = base64_decode($pubkeyid);
openssl_public_encrypt($string, $crypted, $pubkeyid);
}
return base64_encode($crypted);
}
function RSADecryptMessage($string, $key){
$data = "MyEncryptedInternalString";
$parts = explode(":",$key);
$signature = base64_decode($parts[0]);
$pubkeyid = $parts[1];
//$ok = openssl_verify($data, base64_decode($signature), base64_decode($pubkeyid), "sha256WithRSAEncryption");
$pubkeyid = base64_decode($pubkeyid);
openssl_private_decrypt(base64_decode($string), $decrypted, $pubkeyid);
echo "Decrypted text: ". $decrypted;
return $decrypted;
}
$mex = "hello";
//echo RSAEncryptMessage($m,$_GET['key']);
if(isset($_GET['m'])){
echo RSADecryptMessage($_GET['m'],$_GET['key']);
}else{
echo RSAEncryptMessage($mex,$_GET['key']);
}
?>
So when I try to encrypt the content by server-side and then decrypting it in Java it works correctly. I'm assuming to use the generated public key to encrypt the content (sending it to the server) and decrypting the content by using the stored private key on the client too.
The question:
I'm not able to do the contrary: encrypt by client-side and decrypting by server-side using the PHP function RSADecryptMessage. When passing the parameters it doesn't work and writes nothing.
EDIT:
Since I need a communication both sides encrypted to avoid MITM attacks, for example, I use PUBLICKEY generated by the client, then I send the key to the server. So I encrypt my message from the server using the same public key. In this way, from the client, I'm able to decrypt the response by the server using the private key. The best way would be which server generates both public and private key pairs but unfortunately, Java is not able to decrypt a message if the key pair is generated and shared by PHP and that's why I allow the client to generate the key pair. This works. Now I need to do the contrary too, with the same public key sent previously to the server I need to decrypt a message encrypted by the client this time (in the image you can see the string "crypted"). Unfortunately, this seems not to work, because when I call the PHP script, the content is not decrypted.

Solved.
When you want to send an encrypted message from PHP to Java, PHP will
have to encrypt it with the public key from Java. Then Java will
decrypt it with his private key. When you want to send an encrypted
message from Java to PHP, Java will have to encrypt it the public key
from PHP. Then PHP will decrypt it with his private key. Both parties
generate their own key-pair and send the public-key to the other
party. Btw.: Signing does not encrypt the message, the message will
still be visible/readable.
Comment of #Progman
Code.
java:
public static void main(String[] args) throws Exception {
// Generate public and private keys using RSA
Map<String, Object> keys = getRSAKeys();
PrivateKey privateKey = (PrivateKey) keys.get("private");
PublicKey publicKey = (PublicKey) keys.get("public");
StringBuilder keypublic = new StringBuilder();
keypublic.append("-----BEGIN PUBLIC KEY-----\n");
keypublic.append(Base64.getMimeEncoder().encodeToString(publicKey.getEncoded()) + "\n");
keypublic.append("-----END PUBLIC KEY-----\n");
String keyEncodedPublic = Base64.getEncoder().encodeToString(keypublic.toString().getBytes());
String signature = sign("MyEncryptedInternalString", privateKey);
System.out.println("key: \n" + Base64.getEncoder().encodeToString(signature.getBytes()) + ":" + keyEncodedPublic);
System.out.println("\n");
while(true) {
Scanner out = new Scanner(System.in);
System.out.print("Insert text: ");
String enc = out.nextLine();
String descryptedText = decryptMessage(enc, privateKey);
System.out.println("Decrypted: " + descryptedText);
System.out.println();
Scanner out2 = new Scanner(System.in);
System.out.print("Insert text2: ");
String enc2 = out2.nextLine();
byte[] decodedBytesKey = Base64.getDecoder().decode(enc2);
//String content = encryptMessage("message from the client", new String(decodedBytes));
String publicKeyPEM = new String(decodedBytesKey)
.replace("-----BEGIN PUBLIC KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
PublicKey p = keyFactory.generatePublic(keySpec);
System.out.println(encryptMessage("Message from client",p));
}
}
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signature = privateSignature.sign();
return Base64.getEncoder().encodeToString(signature);
}
// Get RSA keys. Uses key size of 2048.
private static Map<String,Object> getRSAKeys() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
Map<String, Object> keys = new HashMap<String,Object>();
keys.put("private", privateKey);
keys.put("public", publicKey);
return keys;
}
private static String decryptMessage(String encryptedText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)));
}
private static String encryptMessage(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return URLEncoder.encode(Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes())));
}
PHP:
<?php
include ("utils/RSA.php");
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "PubKey: " . base64_encode($pubKey) ."<br>";
echo "PrivateKey: " . base64_encode($privKey) . "<br>";
//echo "Encrypted: " . base64_encode($encrypted);
function RSAEncryptMessage($string, $key){
$data = "MyEncryptedInternalString";
$parts = explode(":",$key);
$signature = base64_decode($parts[0]);
$pubkeyid = $parts[1];
$ok = openssl_verify($data, base64_decode($signature), base64_decode($pubkeyid), "sha256WithRSAEncryption");
if ($ok == 1){
$pubkeyid = base64_decode($pubkeyid);
openssl_public_encrypt($string, $crypted, $pubkeyid);
}
return base64_encode($crypted);
}
function RSADecryptMessage($encrypted, $key){
//todo
openssl_private_decrypt(base64_decode($encrypted), $decrypted, base64_decode($key));
echo "Decrypted: " . $decrypted;
}
if((isset($_GET['providemessage']))){
echo RSADecryptMessage($_GET['m'],$_GET['key']);
}else if (isset($_GET['getmessage'])){
$mex = "Message from server";
echo RSAEncryptMessage($mex,$_GET['key']);
}
?>
Screenshots:

Related

How to convert JAVA program to PHP to carryout RSA encryption

I am trying to implement AEPS API but unable to encrypt aadhar number in php. In developer guide they provided method to encrypt using JAVA and i am using php.
Given JAVA code is as follows.
public static String calculateRSA( String salt ) throws InvalidKeyException, Exception {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
byte[] secretMessageBytes = salt.getBytes("UTF-8");
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
String encodedMessage = Base64.encodeBase64String(encryptedMessageBytes);
return encodedMessage;
}
public static PublicKey getPublicKey() throws Exception {
String rawPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaFyrzeDhMaFLx+LZUNOOO14Pj9aPfr+1WOanDgDHxo9NekENYcWUftM9Y17ul2pXr3bqw0GCh4uxNoTQ5cTH4buI42LI8ibMaf7Kppq9MzdzI9/7pOffgdSn+P8J64CJAk3VrVswVgfy8lABt7fL8R6XReI9x8ewwKHhCRTwBgQIDAQAB";
byte[] keyBytes = Base64.decodeBase64(rawPublicKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);// generatePrivate(spec);
}
I tried
$publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaFyrzeDhMaFLx+LZUNOOO14Pj9aPfr+1WOanDgDHxo9NekENYcWUftM9Y17ul2pXr3bqw0GCh4uxNoTQ5cTH4buI42LI8ibMaf7Kppq9MzdzI9/7pOffgdSn+P8J64CJAk3VrVswVgfy8lABt7fL8R6XReI9x8ewwKHhCRTwBgQIDAQAB';
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$plaintext = '828409353766';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$encrypted = $rsa->encrypt($plaintext);
$encrypted = base64_encode($encrypted);

RSA decryption fine with encoded byte array but fails with encoded String [IllegalBlockSizeException] [duplicate]

This question already has an answer here:
RSA encyrption - converting between bytes array and String [duplicate]
(1 answer)
Closed 2 years ago.
we are trying RSA Encryption & Decryption and the issue happens while decrypting. This is our decryption code
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, rsaPrivateKey, oaepParams);
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes());
The encrytpedData is like this
s11Pyj5rrVOfOiWtxpGq+K5D+pYi16CyyX/EwKfMErBkHJ4aVlTmnhrfeCS7LEeXgTs3gkFp96I/oTedG/rXxF2hTAmMH40k0joKJbRtzO858/0dcaaE1uNzr/rI0Jj3ebXPLGhefCMNNpyFH5V4ukVo6vtev5Z9U8oNkUQolbX/r5jJJomkKCCnzGoHMdQg5dafj9Sw/qakO13501YBrkxS0i9ca0GZ8Ll42NwkOZuInh+MAu+gYW4vAr284eJsqgLgTp0+MS1tmfwR6EXgspk1nYR/U84P3MBZAdpmD3nxsVV3iVOCUeoqVyd4kw7M2pvXev6hMbMN4P1nnomo8g==
An error exception was thrown saying javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
We looked into this link getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa, but the issue was with the way we were feeding the encrytpedData.
This is a code we got online
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey pubkey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privkey = (RSAPrivateKey) kp.getPrivate();
// --- encrypt given algorithm string
Cipher oaepFromAlgo = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
oaepFromAlgo.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] ct = oaepFromAlgo.doFinal("chakka".getBytes(StandardCharsets.UTF_8));
// --- decrypt given OAEPParameterSpec
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] pt = oaepFromInit.doFinal(ct);
System.out.println("Printing decoded string");
System.out.println(new String(pt, StandardCharsets.UTF_8));
Here they are supplying the encrypted array directly and works fine, but in our case we are getting encrytpedData as String. Both the codes are same but the supply of encrypted data differs.
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes());
This is where we are getting the exception, so we tried converting the encrytpedData to byte[] in a different way via these two links
RSA encyrption - converting between bytes array and String [duplicate]
IllegalBlockSizeException when trying to encrypt and decrypt a string with AES
So we tried like this
byte[] dec = oaepFromInit.doFinal(Base64.getDecoder().decode(encrytpedData)); which resulted in this javax.crypto.BadPaddingException: Message is larger than modulus.
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes(StandardCharsets.UTF_8)); which gave the same old exception javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes.
Any help would be appreciated
The below full example code is taken from my private cross-platform project and should work. It encrypts a string using RSA encryption with a 2048 key pair and uses OAEP padding with SHA-1 as hash.
The encrypted data are in base64 encoding. For demonstration purpose I'm using static (hardcoded) keys in PEM-format - never ever do this in production.
You can run the code online here: https://repl.it/#javacrypto/CpcJavaRsaEncryptionOaepSha1String
this is the output:
RSA 2048 encryption OAEP SHA-1 string
plaintext: The quick brown fox jumps over the lazy dog
* * * encrypt the plaintext with the RSA public key * * *
ciphertextBase64: pSPayOK79NMPLpaQOp8L7dOTdLeS+jVU5cKPF5mDOvuKtnOjf/NYfgsf1JWa5Ud/fzsXrSN8I/8KAs/freagOYflv6PGUHZ7cYk1iX6sO5cmdD0Mfglj39NxczbqCK3FG20hQfa01ZaOu/dV8+QvVx851ph1nEl8arNML5ohhjIdZTxR3olGouGzDJmuJkDlv2fJICP7sdMnvl7t21QI701I2xR01eatD5src5fY//EIOEjSoTesCBZwEUz1S3UpclNqGONAqaYqlscdTyAlY3Hg8smJRqKWk7ZWKSTYsocBbFeTvcNy75LG/xyILM0l4U+NnwGUypkjR2vJRGVQtw==
* * * decrypt the ciphertext with the RSA private key * * *
ciphertextReceivedBase64: pSPayOK79NMPLpaQOp8L7dOTdLeS+jVU5cKPF5mDOvuKtnOjf/NYfgsf1JWa5Ud/fzsXrSN8I/8KAs/freagOYflv6PGUHZ7cYk1iX6sO5cmdD0Mfglj39NxczbqCK3FG20hQfa01ZaOu/dV8+QvVx851ph1nEl8arNML5ohhjIdZTxR3olGouGzDJmuJkDlv2fJICP7sdMnvl7t21QI701I2xR01eatD5src5fY//EIOEjSoTesCBZwEUz1S3UpclNqGONAqaYqlscdTyAlY3Hg8smJRqKWk7ZWKSTYsocBbFeTvcNy75LG/xyILM0l4U+NnwGUypkjR2vJRGVQtw==
decryptedtext: The quick brown fox jumps over the lazy dog
Security warning: the code does not have any exception handling, uses static (hardcoded) keys and is for educational purpose only.
code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws GeneralSecurityException, IOException {
System.out.println("RSA 2048 encryption OAEP SHA-1 string");
String dataToEncryptString = "The quick brown fox jumps over the lazy dog";
byte[] dataToEncrypt = dataToEncryptString.getBytes(StandardCharsets.UTF_8);
System.out.println("plaintext: " + dataToEncryptString);
// # # # usually we would load the private and public key from a file or keystore # # #
// # # # here we use hardcoded keys for demonstration - don't do this in real programs # # #
String filenamePrivateKeyPem = "privatekey2048.pem";
String filenamePublicKeyPem = "publickey2048.pem";
// encryption
System.out.println("\n* * * encrypt the plaintext with the RSA public key * * *");
PublicKey publicKeyLoad = getPublicKeyFromString(loadRsaPublicKeyPem());
// use this in production
//PublicKey publicKeyLoad = getPublicKeyFromString(loadRsaKeyPemFile(filenamePublicKeyPem));
String ciphertextBase64 = base64Encoding(rsaEncryptionOaepSha1(publicKeyLoad, dataToEncrypt));
System.out.println("ciphertextBase64: " + ciphertextBase64);
// transport the encrypted data to recipient
// receiving the encrypted data, decryption
System.out.println("\n* * * decrypt the ciphertext with the RSA private key * * *");
String ciphertextReceivedBase64 = ciphertextBase64;
//String ciphertextReceivedBase64 = "l4G3O42LtjI9KkzvcF7SQcpqrkOMJw1sWVuI3FCZ1g+Sp/t05E3ZEXyVV/FnadkKVgmpWBifaYPEdKNBTbuts2F1DfrDz1v14lKlMOcqkJB8OmJUAiKJ1ic414R7M5fECKruqkzOdKlTtdb3MI49Ygrzd/cJxOGEvONo3DAOq1kZvZdmyW+K8m807g2qoy833EHyj9NjVZHuDzXi8fMxbIAI5MrN8ykXZBxkFOAGiITEFbGPxu6gBOPJKsPWJ0SVU53CiI1YwGc76/ov4c7FIA1ZeVsJXKo8CEfYuUc7PKIJ3e5Z7CbiNgr4Z5720Xbi0drUBk/LlYq6m8s/zEIMaQ==";
System.out.println("ciphertextReceivedBase64: " + ciphertextReceivedBase64);
PrivateKey privateKeyLoad = getPrivateKeyFromString(loadRsaPrivateKeyPem());
// use this in production
//PrivateKey privateKeyLoad = getPrivateKeyFromString(loadRsaKeyPemFile(filenamePrivateKeyPem));
byte[] ciphertextReceived = base64Decoding(ciphertextReceivedBase64);
byte[] decryptedtextByte = rsaDecryptionOaepSha1(privateKeyLoad, ciphertextReceived);
System.out.println("decryptedtext: " + new String(decryptedtextByte, StandardCharsets.UTF_8));
}
public static byte[] rsaEncryptionOaepSha1 (PublicKey publicKey, byte[] plaintextByte) throws NoSuchAlgorithmException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidAlgorithmParameterException {
byte[] ciphertextByte = null;
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
//OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
// note: SHA1 is the default for Java
OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParameterSpecJCE);
ciphertextByte = encryptCipher.doFinal(plaintextByte);
return ciphertextByte;
}
public static byte[] rsaDecryptionOaepSha1 (PrivateKey privateKey, byte[] ciphertextByte) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
byte[] decryptedtextByte = null;
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
//OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpecJCE);
decryptedtextByte = decryptCipher.doFinal(ciphertextByte);
return decryptedtextByte;
}
private static String base64Encoding(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
private static byte[] base64Decoding(String input) {
return Base64.getDecoder().decode(input);
}
private static String loadRsaPrivateKeyPem() {
// this is a sample key - don't worry !
return "-----BEGIN PRIVATE KEY-----\n" +
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDwSZYlRn86zPi9\n" +
"e1RTZL7QzgE/36zjbeCMyOhf6o/WIKeVxFwVbG2FAY3YJZIxnBH+9j1XS6f+ewjG\n" +
"FlJY4f2IrOpS1kPiO3fmOo5N4nc8JKvjwmKtUM0t63uFFPfs69+7mKJ4w3tk2mSN\n" +
"4gb8J9P9BCXtH6Q78SdOYvdCMspA1X8eERsdLb/jjHs8+gepKqQ6+XwZbSq0vf2B\n" +
"MtaAB7zTX/Dk+ZxDfwIobShPaB0mYmojE2YAQeRq1gYdwwO1dEGk6E5J2toWPpKY\n" +
"/IcSYsGKyFqrsmbw0880r1BwRDer4RFrkzp4zvY+kX3eDanlyMqDLPN+ghXT1lv8\n" +
"snZpbaBDAgMBAAECggEBAIVxmHzjBc11/73bPB2EGaSEg5UhdzZm0wncmZCLB453\n" +
"XBqEjk8nhDsVfdzIIMSEVEowHijYz1c4pMq9osXR26eHwCp47AI73H5zjowadPVl\n" +
"uEAot/xgn1IdMN/boURmSj44qiI/DcwYrTdOi2qGA+jD4PwrUl4nsxiJRZ/x7PjL\n" +
"hMzRbvDxQ4/Q4ThYXwoEGiIBBK/iB3Z5eR7lFa8E5yAaxM2QP9PENBr/OqkGXLWV\n" +
"qA/YTxs3gAvkUjMhlScOi7PMwRX9HsrAeLKbLuC1KJv1p2THUtZbOHqrAF/uwHaj\n" +
"ygUblFaa/BTckTN7PKSVIhp7OihbD04bSRrh+nOilcECgYEA/8atV5DmNxFrxF1P\n" +
"ODDjdJPNb9pzNrDF03TiFBZWS4Q+2JazyLGjZzhg5Vv9RJ7VcIjPAbMy2Cy5BUff\n" +
"EFE+8ryKVWfdpPxpPYOwHCJSw4Bqqdj0Pmp/xw928ebrnUoCzdkUqYYpRWx0T7YV\n" +
"RoA9RiBfQiVHhuJBSDPYJPoP34kCgYEA8H9wLE5L8raUn4NYYRuUVMa+1k4Q1N3X\n" +
"Bixm5cccc/Ja4LVvrnWqmFOmfFgpVd8BcTGaPSsqfA4j/oEQp7tmjZqggVFqiM2m\n" +
"J2YEv18cY/5kiDUVYR7VWSkpqVOkgiX3lK3UkIngnVMGGFnoIBlfBFF9uo02rZpC\n" +
"5o5zebaDImsCgYAE9d5wv0+nq7/STBj4NwKCRUeLrsnjOqRriG3GA/TifAsX+jw8\n" +
"XS2VF+PRLuqHhSkQiKazGr2Wsa9Y6d7qmxjEbmGkbGJBC+AioEYvFX9TaU8oQhvi\n" +
"hgA6ZRNid58EKuZJBbe/3ek4/nR3A0oAVwZZMNGIH972P7cSZmb/uJXMOQKBgQCs\n" +
"FaQAL+4sN/TUxrkAkylqF+QJmEZ26l2nrzHZjMWROYNJcsn8/XkaEhD4vGSnazCu\n" +
"/B0vU6nMppmezF9Mhc112YSrw8QFK5GOc3NGNBoueqMYy1MG8Xcbm1aSMKVv8xba\n" +
"rh+BZQbxy6x61CpCfaT9hAoA6HaNdeoU6y05lBz1DQKBgAbYiIk56QZHeoZKiZxy\n" +
"4eicQS0sVKKRb24ZUd+04cNSTfeIuuXZrYJ48Jbr0fzjIM3EfHvLgh9rAZ+aHe/L\n" +
"84Ig17KiExe+qyYHjut/SC0wODDtzM/jtrpqyYa5JoEpPIaUSgPuTH/WhO3cDsx6\n" +
"3PIW4/CddNs8mCSBOqTnoaxh\n" +
"-----END PRIVATE KEY-----";
}
private static String loadRsaPublicKeyPem() {
// this is a sample key - don't worry !
return "-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8EmWJUZ/Osz4vXtUU2S+\n" +
"0M4BP9+s423gjMjoX+qP1iCnlcRcFWxthQGN2CWSMZwR/vY9V0un/nsIxhZSWOH9\n" +
"iKzqUtZD4jt35jqOTeJ3PCSr48JirVDNLet7hRT37Ovfu5iieMN7ZNpkjeIG/CfT\n" +
"/QQl7R+kO/EnTmL3QjLKQNV/HhEbHS2/44x7PPoHqSqkOvl8GW0qtL39gTLWgAe8\n" +
"01/w5PmcQ38CKG0oT2gdJmJqIxNmAEHkatYGHcMDtXRBpOhOSdraFj6SmPyHEmLB\n" +
"ishaq7Jm8NPPNK9QcEQ3q+ERa5M6eM72PpF93g2p5cjKgyzzfoIV09Zb/LJ2aW2g\n" +
"QwIDAQAB\n" +
"-----END PUBLIC KEY-----";
}
public static PrivateKey getPrivateKeyFromString(String key) throws GeneralSecurityException {
String privateKeyPEM = key;
privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "");
privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
privateKeyPEM = privateKeyPEM.replaceAll("[\\r\\n]+", "");
byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
PrivateKey privKey = (PrivateKey) kf.generatePrivate(keySpec);
return privKey;
}
public static PublicKey getPublicKeyFromString(String key) throws GeneralSecurityException {
String publicKeyPEM = key;
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replaceAll("[\\r\\n]+", "");
byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
return pubKey;
}
private static String loadRsaKeyPemFile(String filename) throws IOException {
return new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
}
}

Problem with decryption of AES key with RSA and message decryption

I am working on secure chat application. I have AES key for ecrypt/decrypt message and users have own public/private RS keys for encrypt/decrypt AES key. My code give me error like this:
> javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:383)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:294)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at org.fastchat.User.decryptAESKey(User.java:183)
at org.fastchat.User.readMessage(User.java:210)
at org.fastchat.WatchInbox.startWatch(WatchInbox.java:59)
at org.fastchat.WatchInbox.run(WatchInbox.java:32)
Error is in function for decrypting AES key with RSA private key. I found that problem could be with wrong key (keys stored in serialization, every user have once generated keys in profile object) or encode/decode problems. I decide to store encrypted AES key in some file and read that file for decrypt AES key. Is there some better way for store encypted AES key? Am I doing encode/decode in right way? Any help is welcome, I dont have any ideas now. My code is here and every part of proccess is in different function.
public SecretKey generateAESkey() throws NoSuchAlgorithmException {
System.out.println("Generating AES key...\n");
SecureRandom random = new SecureRandom();
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, random);
SecretKey aeSecretKey = keyGenerator.generateKey();
System.out.println("AES1 KEY " + new String(Base64.getEncoder().encodeToString(aeSecretKey.getEncoded())));
System.out.println("===========================\n");
return aeSecretKey;
// return keyGenerator.generateKey();
}
public byte[] encryptAESKey(SecretKey key, PublicKey pubKey) throws Exception {
System.out.println("Encrypt AES key...\n");
String aesKey = new String(Base64.getEncoder().encodeToString(key.getEncoded()));
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] aesEnc = cipher.doFinal(aesKey.getBytes());
System.out.println("AES ENCRYPTED: " + aesEnc);
System.out.println("==========================\n");
return aesEnc;
// return cipher.doFinal(aesToEnc);
}
public byte[] encryptMessage(String message, SecretKey aeSecretKey) throws Exception {
System.out.println("Encrypt message...\n");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aeSecretKey);
byte[] msgBytes = message.getBytes(); // This will be encrypted
byte[] msgEnc = cipher.doFinal(msgBytes);
System.out.println("=============================\n");
return msgEnc;
// return cipher.doFinal(msgBytes); //This will be in .txt file
}
public void checkerUpdate(User receiver) throws IOException {
BufferedWriter check = new BufferedWriter(new FileWriter(receiver.getCheck() + "/" + getUsername() + ".txt"));
Random random = new Random();
Integer num = random.nextInt(100);
check.write(num);
check.close();
}
public void sendMessage(String message, User receiver) throws Exception {
// First generate AES key
SecretKey aesSecretKey = generateAESkey(); // keysize = 128
// Encrypt message with AES key, will be in file
byte[] encMsg = encryptMessage(message, aesSecretKey);
// Encrypt AES key, put in file
byte[] aesEnc = encryptAESKey(aesSecretKey, receiver.getPub());
// Send message and key to receiver
FileOutputStream msgWrite = new FileOutputStream(receiver.getInbox() + "/" + getUsername() + ".msg", true);
FileOutputStream keyWrite = new FileOutputStream(receiver.getInbox() + "/" + getUsername() + ".kgn", true);
keyWrite.write(Base64.getEncoder().encode(aesEnc));
msgWrite.write(Base64.getEncoder().encode(encMsg));
keyWrite.close();
msgWrite.close();
// Add file to CHECKER, temp operations for WatchInbox service
checkerUpdate(receiver);
}
// FUNCTIONS FOR DECRYPTION
public byte[] decryptAESKey(byte[] aesEnc) throws Exception {
System.out.println("Decrypt AES key...\n");
byte[] aesEncString = Base64.getDecoder().decode(aesEnc);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, getPriv());
byte[] decAes = cipher.doFinal(aesEncString);
System.out.println("===========================\n");
return decAes;
// return cipher.doFinal(Base64.getDecoder().decode(aesEnc));
}
public String decryptMessage(byte[] msg, SecretKeySpec aeskey) throws Exception {
System.out.println("Decrypt message...\n");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aeskey);
String msgDec = cipher.doFinal(Base64.getDecoder().decode(msg)).toString();
System.out.println("============================\n");
return msgDec;
// return cipher.doFinal(Base64.getDecoder().decode(msg)).toString();
}
public String readMessage(User sender) throws Exception {
// Read file in inbox
File msgtoRead = new File(getInbox() + "/" + sender.getUsername() + ".msg");
FileInputStream keytoRead = new FileInputStream(getInbox() + "/" + sender.getUsername() + ".kgn");
// Read 128bits from filetoRead. That is encrypted key.
byte[] aesEnc = new byte[128];
keytoRead.read(aesEnc);
// Decrypted aes key for decode
byte[] aesDec = decryptAESKey(aesEnc);
SecretKeySpec aesKey = new SecretKeySpec(aesDec, "AES/CBC/PKCS5Padding");
// Read message
byte[] message = Files.readAllBytes(msgtoRead.toPath());
keytoRead.close();
// Decrypt message with loaded AES key (aesKey), return this
return new String(decryptMessage(message, aesKey));
}

Getting Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 26 bytes while decrypting encoded text

I am trying to decrypt a request encrypted using AES algorithm with the RSA encrypted AES secret key. The encryptedText is the text which I have to decode using encryptedAESKeyStringinString key.
String encryptedText = "motnHul049AJSIo5RiOr7Njg3gV85LSR7DxxTjT6UlN_Vdi0q7hw9XDTUyiJ7XCtaObJDOWPwXGeT73JQKwN-GW6Pg6fkgyRlbmqNM23_DjqFQG7NqhhwdRfVJ4FfGnB1sZMcsSi0YwtKVOfTQu11coQm-LnWSW3o05-A4B7X4";
// Generate public and private keys using RSA
Key privateKey = getPrivate("KeyPair/key.jks");
System.out.println("Private key :" + privateKey);
Key publicKey = getPublic("KeyPair/key.jks");
System.out.println("Public key :" + publicKey);
//Encrypted AES secret key using RSA public key
String encryptedAESKeyStringinString = "SGvzL3jbTucB6mFSrGDHGI19OKuLe2u0miGnmb6EfgIHgiWqGfvGI5hd2U8-owYKThORbY6IZWyUsFKFc2CsegMKGkUBbnKHz-BUbrC5jNPHeW2LxNW_SLKZMmVciwWqHtcsQkUhGn1ZpEwgYp7NccP2qQJ1K5wY0G22ssoXsr6_gf4aMAafpP_EU8bV6yfOziaNWdOI0mkBshC6uYi2xibCBFWhP0HYouxEjuoLa7oXDSr1-Pol7S4tFibv8P92GlEqHuspjkBEk-crBVEMwPYZ5CjlVg0a8NXofvRYJIPOWHFDP03ALnKUmhGDv5pq7qbyhM-GwLFDncOU466VTw";
//Decryption of AES key
String decryptedAESKeyString = decryptAESKey(encryptedAESKeyStringinString, privateKey);
System.out.println("Decrypted AES key with RSA "+decryptedAESKeyString);
// Now decrypt data using the decrypted AES key!
String decryptedText = decryptTextUsingAES(encryptedText, decryptedAESKeyString);
System.out.println("decrypted: " + decryptedText);
//decryptTextUsingAES() method
public static String decryptTextUsingAES(String encryptedText, String aesKeyString) throws Exception {
//byte[] decodedKey = Base64.getUrlDecoder().decode(aesKeyString.getBytes("UTF-8"));
byte[] decodedKey = Base64.getUrlDecoder().decode(aesKeyString);
System.out.println("decodedKey->"+decodedKey);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
//byte[] encPass = Base64.decodeBase64(aesKeyString.getBytes("UTF-8"));
//SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
//SecretKey aesKey = new SecretKeySpec(aesKeyString.getBytes("UTF-8"), "AES");
System.out.println("AES key :"+ originalKey);
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] bytePlainText = aesCipher.doFinal(Base64.getUrlDecoder().decode(encryptedText));
return new String(bytePlainText);
}
//decryptAESKey() method
private static String decryptAESKey(String encryptedAESKey, Key privateKey) throws Exception {
byte[] encBytes = Base64.getUrlDecoder().decode(encryptedAESKey.trim().getBytes("UTF-8"));
System.out.println("encBytes=="+encBytes);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(encBytes));
}
//Getting public and private key
public static Key getPrivate(String filename) throws Exception {
String password = "123456";
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, password.toCharArray());
String alias = "rib_pub_priv_ob";
Key key = keystore.getKey(alias, password.toCharArray());
return key;
}
//https://docs.oracle.com/javase/8/docs/api/java/security/spec/X509EncodedKeySpec.html
public static Key getPublic(String filename) throws Exception {
String password = "123456";
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, password.toCharArray());
Enumeration aliases = keystore.aliases();
//LOG.info("Loaded aliases..........."+aliases);
String aliasName = null;
if (aliases.hasMoreElements()) {
aliasName = (String)aliases.nextElement();
}
//String alias = "cib.icicibank.com";
String alias = "rib_pub_priv_ob";
Key key = keystore.getCertificate(alias).getPublicKey();
// Get certificate of public key
java.security.cert.Certificate cert = keystore.getCertificate(alias);
// Get public key
PublicKey publicKey = cert.getPublicKey();
//System.out.println("Publickey->"+publicKey);
return key;
}
//Output
Private key success
Private key :sun.security.rsa.RSAPrivateCrtKeyImpl#ffd2dcac
Public key success
Public key :Sun RSA public key, 2048 bits
modulus: 18213722380296769419176290383978262259711510121564750763778723301212945343757780419548592815669767026269432578044929215041238216136582555682984918038025714579636338218912893485917045613716952330026484856385185507103281153339648026845099146147505703575013284525178116844264542711761691005405946223414048773983620990969094260489552973361717030169183023097170355217065004855506605954167676904790917459796930427392967698905896378678786481959179236540862580781084688615759803403218899513555331743203995382479570969849672080854328076415494976227353539015464213594405750368178401939001834233806304211309666500156295537454433
public exponent: 65537
encBytes==[B#2d6d8735
Decrypted AES key with RSA Pf03zku5GNElJlOXAZkYRg6LbeZttkMKCdL
decodedKey->[B#de0a01f
AES key :javax.crypto.spec.SecretKeySpec#17c6b
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 26 bytes
at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:87)
at com.sun.crypto.provider.ElectronicCodeBook.init(ElectronicCodeBook.java:94)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:467)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
at javax.crypto.Cipher.implInit(Cipher.java:802)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at demo123.AESwithRSA.decryptTextUsingAES(AESwithRSA.java:144)
at demo123.AESwithRSA.main(AESwithRSA.java:79)

Can't restore privateKey RSA

I have this issue about java cryptography.
I take a password from the user then I product a private key and a public key.From the public key I create the cipher and then I store the private key and the cipher.
Then from my second application I read the password again from the user , the cipher file and the private key and then I try to match the password with the decryption of the cipher and the private Key.
My first application:
private static byte[] encrypt(byte[] inpBytes, PublicKey key,
String xform) throws Exception {
Cipher cipher = Cipher.getInstance(xform);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(inpBytes);
}
String xform = "RSA";
// Generate a key-pair
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Efarmogi_1.class.getName()).log(Level.SEVERE, null, ex);
}
kpg.initialize(512); // 512 is the keysize.
KeyPair kp = kpg.generateKeyPair();
/create public and private key
PublicKey pubk = kp.getPublic();
PrivateKey prvk = kp.getPrivate();
//password from user
String password = T_Password.getText();
byte[] dataBytes = password.getBytes();
//create cipher
byte[] encBytes = null;
try {
encBytes = encrypt(dataBytes, pubk, xform);
} catch (Exception ex) {
Logger.getLogger(Efarmogi_1.class.getName()).log(Level.SEVERE, null, ex);
}
//storing
//cipher
FileOutputStream cipher = null;
try {
cipher = new FileOutputStream( "Xrhstes\\"+T_Username.getText()+"\\hash_"+T_Username.getText());
cipher.write(encBytes);//write with bytes
cipher.close();
} catch (IOException ex) {
Logger.getLogger(Efarmogi_1.class.getName()).log(Level.SEVERE, null, ex);
}
//private key
byte[] key2 = prvk.getEncoded();
FileOutputStream keyfos2 = null;
try {
keyfos2 = new FileOutputStream("Xrhstes\\"+T_Username.getText()+"\\private_"+ T_Username.getText()+".pem");
keyfos2.write(key2);
keyfos2.close();
and this is the second application:
private static byte[] decrypt(byte[] inpBytes, PrivateKey key,String xform) throws Exception{
Cipher cipher = Cipher.getInstance(xform);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(inpBytes);
}
//fetch private key
byte[] prvk1 = new byte[(int)new File("C:\\...\\"+T_Username.getText()+"\\private_"+ T_Username.getText()).length()];
//make it from bytes to private key
KeyFactory kf= KeyFactory.getInstance("RSA");
PrivateKey prvk=kf.generatePrivate(new PKCS8EncodedKeySpec(prvk1));
//fetch cipher
byte[] encBytes = new byte[(int)new File("C:\\...\\"+T_Username.getText()+"\\hash_"+ T_Username.getText()).length()];
//decrypt with our password given from user
String xform = "RSA";
byte[] decBytes = decrypt(encBytes,prvk, xform);
boolean expected = java.util.Arrays.equals(password, decBytes);
System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!"));
My issue is when I try to retransform the bytes saved , back to privateKey I get multiple errors that key type is invalid(problem starts at decoding PKCS8EncodedKeySpec it is noted that KeySpec is invalid).I tried numerous ways but still the same,could someone guide me where is my mistake ? thanks in advance!!!
With the following lines:
byte[] prvk1 = new byte[(int)new File("C:\\...\\"+T_Username.getText()+"\\private_"+ T_Username.getText()).length()];
and
byte[] encBytes = new byte[(int)new File("C:\\...\\"+T_Username.getText()+"\\hash_"+ T_Username.getText()).length()];
You actually create two empty byte arrays. You only indicate the size of the array using File.length(), which obviously is not correct. Try again after actually reading the files, e.g. using the readAllBytes method (requires Java 8 or higher).

Categories