I have generated a public and private code with puttygen, the private key is exported as openssl, the name of the peys are public_key.der , private_key.pem but when i try to use java to encrypt it i get this error:
java.io.FileNotFoundException: public_key.der
The codode is :
public static String RSAPublicEncryptuion(String text){
DataInputStream dis = null;
try {
File pubKeyFile = new File("public_key.der");
dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] keyBytes = new byte[(int) pubKeyFile.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String textoEncryptado = new String(cipher.doFinal(text.getBytes()), "UTF-8");
return textoEncryptado;
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error";
}
The public_key are in the same package than this class (testras.ras), what i'm doing wrong ?
Thanks for all!
Sorry for my bad English
Your current approach (using a relative filepath) depends on the location of the key file relative to the working directory at runtime, which can be non-obvious.
However, you mention that the public key file is "in the same place where the .class" file is -- you can leverage this fact to gain a more flexible solution. Try using Class.getResourceAsStream, as illustrated below:
InputStream is = RSAEncrypt.class.getResourceAsStream("public_key.der");
Related
In my application I want to download an HTML file from server, then decrypt this file and show into webView!
The backend developer uses this library for encrypt file from server: https://github.com/soarecostin/file-vault
I wrote the code below, but when decrypting a file, it shows an error in Logcat and doesn't decrypt this file!
My code:
encryptionPassword = "7BOF%aZQMpfJ#2wUS*S6!#K+ZB$Sz+J0";
String inputFile = FileUtils.getDirPath(this) + "/BookFile_716798.html";
String outPutFile = FileUtils.getDirPath(this) + "/BookFile_716798_decrypt.html";
try {
decrypt(inputFile, encryptionPassword, outPutFile);
Log.e("DecryptLog", "0");
} catch (IOException e) {
e.printStackTrace();
Log.e("DecryptLog", "1");
Log.e("DecryptLog", "" + e.getMessage());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.e("DecryptLog", "2");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
Log.e("DecryptLog", "3");
} catch (InvalidKeyException e) {
e.printStackTrace();
Log.e("DecryptLog", "4");
}
private void decrypt(String path, String password, String outPath)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(path);
FileOutputStream fos = new FileOutputStream(outPath);
byte[] key = (password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec sks = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}
This message is shown in logCat:
2020-07-31 21:52:39.881 1367-1367/com.app.app E/DecryptLog: 1
2020-07-31 21:52:39.881 1367-1367/com.app.appE/DecryptLog: javax.crypto.BadPaddingException: pad block corrupted
How can I fix it?
CipherText
i5SvmG2TbtZfkWdwJ5qeaYzvLlQknY3uMvZxSEwhBdRcXKHjgzrRk6XLDCEG9ZtZDGDA7iB3tFhLPMisfqGZvSSrcBfiV8b71+qzWVDNW9EedVShk6kaeEN6rw4UgVi6P5PvrDMn6pmYmLWCjtuFWrmboCvvYgI+FJurhlbsQESkA5oDYirjS8L0wnsQB/TnnQ5UPY2xfOBdY2MJpUSTyIjJPhI40GST8YWjXEMkJeDV/1zuKuK55RHCDF5AdTMEvgvvRnGhN2Fzh+rsDziHqVS9d8FmrtjdU445F6ki0d8DkaeFfrofptxGIncqfuukKSXpSp4cPLvM3LxtRvp+Aw==
Code to decrypt
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp2 = kpg.generateKeyPair();
generatedPub = kp2.getPublic();
generatedPvt = kp2.getPrivate();
public String rsaDecrypt(String encrypted) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, generatedPvt);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted.getBytes()));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Error
javax.crypto.BadPaddingException: error:04000089:RSA routines:OPENSSL_internal:PKCS_DECODING_ERROR
Also, if I try printing the private key as :
generatedPvt.toString()
I get the following :
OpenSSLRSAPrivateCrtKey{modulus=c7544bf521bbdd7db52dd28bd3c6f694214dc2356b905edd2730b631d11be9aea703692c2db690e6725da65737b5ec511c13668d1735bfbbc2519e0d33a67b41b289bae6ea71903af91e4f12c6e8660614ef12cd439293a0a38f564fd8f19a3e38f9e2defa269d0bcf0f53159bba1b4fd539ad934fb691e860113be53901de5a10d0c0e3ceaec3715841bc6e56b7738336e8df95a989b61175b06d70d349dcb4a031acf5b25647a1d77f6e6e11efc66e98bb321430f148a63c103a0a59e94b147a4fb49a9ecb0b23603a6ceed6e6e298650667cd61de71455bd4f95767444d89bcf485cc47a297b5306a60a14f77a3fbc19552c5fddfa5cfa2e68020e245ad91,publicExponent=10001}
While I was expecting the PKCS#8 formatted key to be printed. How do i get the key printed in the PKCS#8 format ?
And why am i getting the padding error as shown above ?
byte[] original = cipher.doFinal(encrypted.getBytes());
remove Base64.decodeBase64 from both encrypt and decrypt methods
if you want to convert key to string then use
String keyString= Base64.encodeBase64String(key.getEncoded());
RSA Implementation
public static void main(String[] args) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp2 = kpg.generateKeyPair();
PublicKey publicKey = kp2.getPublic();
PrivateKey privateKey = kp2.getPrivate();
NewClass nc = new NewClass();
byte[] encrypt=nc.rsaEncrypt("hi",publicKey);
byte[] decrypt=nc.rsaDecrypt(encrypt,privateKey);
String decryptString = new String(decrypt);
System.out.println("decryptString = " + decryptString);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
public byte[] rsaDecrypt(byte[] encrypted,PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] original = cipher.doFinal(encrypted);
return original;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public byte[] rsaEncrypt(String message,PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] original = cipher.doFinal(message.getBytes());
return original;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
When encoding and decoding is done along with encrypt and decrypt the order must be
Encryption
cipher.doFinal(Base64.encodeBase64(message.getBytes()));
Decryption
Base64.decodeBase64(cipher.doFinal(cipher.getBytes()));
I am currently trying to implement McEliece encryption using BC but running into some trouble. I currently have the capabilities to create the keys and place them into a file, i can read them back into the program but cannot get it to go from bytes back to Public Key.
Below is what i currently have:
public static String EncryptText(Component tmp, String Plaintext) throws InvalidKeyException, InvalidCipherTextException {
String CipherText = "Didnt Work";
try {
// The message to encrypt.
byte[] messageBytes = Plaintext.getBytes();
//read in the Public Key to use to Encrypt.
File f = new File(tmp.getPublicKey());
FileInputStream fis = new FileInputStream(f);
byte[] PubKeybytes = new byte[fis.available()];
fis.read(PubKeybytes);
fis.close();
//turn the bytes into the Key.
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubKeybytes);
SubjectPublicKeyInfo PKI ;
KeyFactory KF = null;
try {
KF = KeyFactory.getInstance("McEliece");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(McEliecePKCS.class.getName()).log(Level.SEVERE, null, ex);
}
PublicKey PK = null;
try {
PK = KF.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(McEliecePKCS.class.getName()).log(Level.SEVERE, null, ex);
}
//Public Key
PublicKey aPublic = PK;
McEliecePublicKeyParameters GPKP = (McEliecePublicKeyParameters) McElieceKeysToParams.generatePublicKeyParameter(aPublic);
//set the public key to use.
McElieceCipher EnCipheredText = new McElieceCipher();
EnCipheredText.init(true, GPKP);
EnCipheredText.initCipherEncrypt(GPKP);
byte[] ciphertextBytes;
//sign the message with the public key.
ciphertextBytes = EnCipheredText.messageEncrypt(messageBytes);
CipherText = new String(ciphertextBytes);
return CipherText;
} catch (IOException ex) {
Logger.getLogger(McEliecePKCS.class.getName()).log(Level.SEVERE, null, ex);
}
return CipherText;
}\
The current error im having with this code is with the KeyFactory and that "McEliece" is not considered an algorithm as im getting NoSuchAlgorithmException but im not really sure what else to try at the moment. i have also tried to use the KeyFactory that is included with BouncyCastle for McEliece but had no success as the methods were either protected or did not allow for KeySpec and wanted SubjectPublicKeyInfo which i could not figure out how to change the KeySpec into or the Byte array into.
Sorry if this is a simple question im fairly new to coding Cryptography.
Thanks for the replies in advance.
Managed to figure out the issue. i needed to add:
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastlePQCProvider());
I have the following pieces of code:
Globals
public static PublicKey pubKey;
public static PrivateKey privKey;
public static Cipher cip;
Main
public static void main(String[] args) throws Exception {
//Generate the keys
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");
cip = Cipher.getInstance("RSA/ECB/NoPadding");
// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicKey.getEncoded());
FileOutputStream fos = new FileOutputStream("public.key");
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();
// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
privateKey.getEncoded());
fos = new FileOutputStream("private.key");
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
//Get the public and private keys out of their files
getPubAndPrivateKey();
//Check if the keys gotten out of the files are the same as the generated files (this returns truetrue)
System.out.print(publicKey.equals(pubKey));
System.out.print(privateKey.equals(privKey));
byte[] text = "This is my super secret secret".getBytes();
encryptToFile("encrypted.txt", text );
decryptToFile("encrypted.txt", "decrypted.txt");
}
Getting the keys from the files
private static void getPubAndPrivateKey() throws IOException, Exception {
// Read Public Key.
File filePublicKey = new File("public.key");
FileInputStream fis = new FileInputStream("public.key");
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();
// Read Private Key.
File filePrivateKey = new File("private.key");
fis = new FileInputStream("private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
pubKey = keyFactory.generatePublic(publicKeySpec);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
privKey = keyFactory.generatePrivate(privateKeySpec);
}
Encrypting
public static void encryptToFile(String fileName, byte[] data)
throws IOException {
try {
cip.init(Cipher.ENCRYPT_MODE, privKey);
byte[] cipherData = cip.doFinal(data);
String encryptedData = cipherData.toString();
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(encryptedData);
out.close();
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
}
}
Decrypting
private static void decryptToFile(String string, String string2)
throws Exception {
try {
File encryptedFile = new File("encrypted.txt");
byte[] encrypted = getContents(encryptedFile).getBytes();
cip = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cip.init(Cipher.DECRYPT_MODE, pubKey);
byte[] cipherData = cip.doFinal(encrypted);
String decryptedData = cipherData.toString();
BufferedWriter out = new BufferedWriter(new FileWriter(
"decrypted.txt"));
out.write(decryptedData);
out.close();
} catch (Exception e) {
throw e;
}
}
Things I already checked
The data used in the decryption is the same as in the encrypted file
The generated keys are the same as the ones gotten from the file
The encryption and decryption both don't give errors
Results
Original string:
My super secret secret
The encryption results in:
[B#1747b17
The decryption results in:
[B#91a4fb
If you print out a byte array via toString() method you are getting a value that is totally independent of the content.
Therefore the values [B#1747b17 [B#91a4fb are just garbage that does not tell you anything.
If you want to print the content of a byte array convert it to Base64 or hex-string.
System.out.println(new sun.misc.BASE64Encoder().encode(myByteArray));
A hex string can be generated by using org.apache.commons.codec.binary.Hex from Apache Commons Codec library.
I agree with the above answer.
I would like to add that in your case, you can simply use FileOutputStream, write the bytes to a file -
For example:
public static void encryptToFile(String fileName, byte[] data)
throws IOException {
FileOutputStream out = null;
try {
cip.init(Cipher.ENCRYPT_MODE, privKey);
byte[] cipherData = cip.doFinal(data);
out = new FileOutputStream(fileName);
out.write(cipherData);
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
}
}
}
}
I need to replace the encrypt and decrypt step from Unix to java code with the rsaprivatekey.pem and rsapublickey.pem keys generated with openssl
I generate the keys
openssl genrsa -out /tmp/rsaprivatekey.pem -des3 1024
openssl rsa -in /tmp/rsaprivatekey.pem -pubout -out /tmp/rsapublickey.pem
i use the keys in unix (i need do it in java)
echo "Text to encript"| openssl rsautl -encrypt -inkey /tmp/rsapublickey.pem -pubin -out out.enc
openssl rsautl -decrypt -inkey /tmp/rsaprivatekey.pem -in out.enc
This was my attempt to do it
public static void main(String[] args) {
Base64 base64 = new Base64();
String TextStream = "this is the input text";
byte[] Cipher;
System.out.println("input:\n" + TextStream);
Cipher = encrypt(TextStream);
System.out.println("cipher:\n" + base64.encodeAsString(Cipher));
System.out.println("decrypt:\n" + decrypt(Cipher));
}
private static byte[] encrypt(String Buffer) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, getPrivateKey(PRIVATE_PATH));
return rsa.doFinal(Buffer.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String decrypt(byte[] buffer) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, getPrivateKey(PUBLIC_PATH));
byte[] utf8 = rsa.doFinal(buffer);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static PrivateKey getPrivateKey(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
public static PublicKey getPublicKey(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
but it not works, the PKCS8EncodedKeySpec/X509EncodedKeySpec are not correct... but i do not know what to put
Solution:
Thanks to #Sanjeev, using the bouncy castle API, I was able to encrypt/decrypt with the keys generated by openssl
public static void main(String[] args) throws IOException {
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair = readKeyPair(new File(PRIVATE_PATH), "pass");
// if the private key is not encripted, pass can be anything.
Key publickey = readPublicKey(new File(PUBLIC_PATH), "pass");
Base64 base64 = new Base64();
String text = "this is the input text";
byte[] encripted;
System.out.println("input:\n" + text);
encripted = encrypt(keyPair.getPublic(), text);
System.out.println("cipher:\n" + base64.encodeAsString(encripted));
System.out.println("decrypt:\n" + decrypt(keyPair.getPrivate(), encripted));
}
private static byte[] encrypt(Key pubkey, String text) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, pubkey);
return rsa.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String decrypt(Key decryptionKey, byte[] buffer) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, decryptionKey);
byte[] utf8 = rsa.doFinal(buffer);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static KeyPair readKeyPair(File privateKey, String keyPassword) throws IOException {
FileReader fileReader = new FileReader(privateKey);
PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword.toCharArray()));
try {
return (KeyPair) r.readObject();
} catch (IOException ex) {
throw ex;
} finally {
r.close();
fileReader.close();
}
}
private static Key readPublicKey(File privateKey, String keyPassword) throws IOException {
FileReader fileReader = new FileReader(privateKey);
PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword.toCharArray()));
try {
return (RSAPublicKey) r.readObject();
} catch (IOException ex) {
throw ex;
} finally {
r.close();
fileReader.close();
}
}
I think you're having problems reading PEM files. The JPA doesn't directly support the PEM format. You have two options, either convert them to DER encoded files (you can use openSSL to do this) or the you can use the bouncy castle API to read (or write) PEM files. the class you'd be interested in is called PEMReader (and maybe also PEMWriter). Here is the Javadoc on the bouncycastle website.