Program is running now. It runs but then crashes. In my files folder it creates an encrypted file but it is blank. It also does not produce a decrypted file at all. I also changed the bit size to 128. What else I am missing in order to properly implement AES?
This is the modified program
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.DESKeySpec;
public class MyCiphers {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("key.txt"));
String key = br.readLine();
br.close();
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("encrypted.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("encrypted.txt");
FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
SecretKeySpec dks = new SecretKeySpec(key.getBytes(),"AES");
Cipher cipher = Cipher.getInstance("AES");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, dks);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, dks);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[128];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
As the error message says, there is no method getBytes() for the type InputStream.
You need to read the key and store it as a String.
eg.
rather than FileInputStream fisk ... do
BufferedReader br = new BufferedReader(new FileReader("Key.txt"));
String key = br.readLine();
br.close();
(assuming that your key file just contains the key on one line)
Then change your encrypt/decrypt and encryptOrDecrypt methods to take in the key as a String rather than InputStream
eg. encrypt(String key, InputStream is, OutputStream os)
Then you can call SecretKeySpec(key.getBytes(),"DES");
Also you realise that this is DES, not AES as you say right? If you want to use AES you will need a 128 bit key (or 192/256 bits)
Related
creating a server-client java App for encryption and Decryption using DES algorithm and a file to save my key in it ,socket for client server comunication
i have problem in the decrypt function
this is my server code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import javax.crypto.*;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.spec.SecretKeySpec;
/**
*
* #author ASUS
*/
public class Server {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
try (ServerSocket listener = new ServerSocket(3001)) {
System.out.println("The date server is running...");
while (true) {
try (Socket socket = listener.accept()) {
Key k = Client.getkey("D://key.txt");
DataInputStream in = new DataInputStream(socket.getInputStream());
String x = in.readUTF();
System.out.println(k);
System.out.println(x);
System.out.println(Decrypt(x, k));
}
}
}
}
public static String Decrypt(String cipherText, Key k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, k);
return new String (cipher.doFinal(Base64.getDecoder().decode(cipherText)),"UTF-8");
}
public static void gen_key() throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key k = kg.generateKey();
String encodedKey = Base64.getEncoder().encodeToString(k.getEncoded());
try {
FileWriter myWriter = new FileWriter("D://key.txt");
myWriter.write(encodedKey);
myWriter.close();
System.out.println("Successfully wrote key to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static Key getkey(String filename) throws FileNotFoundException, IOException {
InputStream is = new FileInputStream(filename);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line = buffer.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line);
line = buffer.readLine();
}
String fileAsString = sb.toString();
byte[] decodedkey = Base64.getDecoder().decode(fileAsString);
SecretKey originkey = new SecretKeySpec(decodedkey, 0, decodedkey.length, "DES");
return originkey;
}
}
and this is client code
import java.io.BufferedReader;
import java.io.File;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.crypto.*;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.spec.SecretKeySpec;
/**
*
* #author ASUS
*/
public class Client {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
gen_key();
byte[] r;
Key k=getkey("D://key.txt");
r = encrypt("fatimaalzahrasha",k);
Socket socket = new Socket("127.0.0.1", 3001);
DataOutputStream os=new DataOutputStream(socket.getOutputStream());
os.writeUTF(r.toString());
}
public static Key getkey(String filename) throws FileNotFoundException, IOException{
InputStream is=new FileInputStream(filename);
BufferedReader buffer=new BufferedReader(new InputStreamReader(is));
String line=buffer.readLine();
StringBuilder sb=new StringBuilder();
while(line!=null)
{sb.append(line);
line=buffer.readLine();}
String fileAsString=sb.toString();
byte[] decodedkey=Base64.getDecoder().decode(fileAsString);
SecretKey originkey=new SecretKeySpec(decodedkey, 0,decodedkey.length,"DES");
return originkey;}
public static void gen_key() throws NoSuchAlgorithmException{
KeyGenerator kg=KeyGenerator.getInstance("DES");
Key k=kg.generateKey();
String encodedKey=Base64.getEncoder().encodeToString(k.getEncoded());
try {
FileWriter myWriter = new FileWriter("D://key.txt");
myWriter.write(encodedKey);
myWriter.close();
System.out.println("Successfully wrote key to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static byte [] encrypt(String plain,Key k ) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] data = plain.getBytes();
byte[] result = cipher.doFinal(data);
return result;
}
}
when i run server then client i have this output
The date server is running...
javax.crypto.spec.SecretKeySpec#fffe78c8
[B#1412c2f
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 5b
at java.util.Base64$Decoder.decode0(Base64.java:714)
at java.util.Base64$Decoder.decode(Base64.java:526)
at Server.Decrypt(Server.java:60)
at Server.main(Server.java:48)
C:\Users\ASUS\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 11 seconds)
The error results of different formats of the encrypted text ("ciphertext"). On client side the output of the encrypt method is a byte array that get transferred via Socket to the server. On server side the input of the decryption method awaits a string in Base64-encoding.
So you can send the encrypted data as a byte array and leave out the decoding part OR you encode your byte array on client side with Base64 like
byte[] r;
r = encrypt("fatimaalzahrasha",k);
String rBase64 = Base64.getEncoder().encodeToString(r);
os.writeUTF(rBase64);
I am working on a Encryption/Decryption program in Java. I am using a key called "secret1234" to encrypt and decrypt a message from a text file. This program uses a string for the key. However, I am interested in using a number (integer) for the key so I can generate random numbers. So, how can this program be modified to allow the key to be an integer and not a string for encrypting and descrypting the message?
This is the program:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class Program {
public static void main(String[] args) {
try {
String key = "secret1234";// This is the key
FileInputStream fis = new FileInputStream("text.txt");//text.txt is a text file with a short message
FileOutputStream fos = new FileOutputStream("encryptedText.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("encryptedText.txt");
FileOutputStream fos2 = new FileOutputStream("decryptedText.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
Use this in your code to generate the key:
String key = String.valueOf(SecureRandom.getInstance("SHA1PRNG").nextInt());
I'm writing a program which takes as input from the console - the name of a zip file, name of a zip file to be made containig the encrypted files generate from the first zip and a file containing the public key. I get an exception every time the stream closes:
Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 11 but got 128 bytes)
at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:288)
at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:361)
at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:238)
at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:378)
at javax.crypto.CipherOutputStream.close(CipherOutputStream.java:217)
at com.Main.main(Main.java:107)
How can I fix this? The code is bellow:
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
public class Main {
public final static int BUFFER_SIZE = 1024;
public static String getPublicKeyString(String fileName){
String key = new String();
try {
BufferedReader buf = new BufferedReader(new FileReader(fileName));
key = buf.readLine();
} catch ( IOException e) {
e.printStackTrace();
}
return key.trim();
}
public static PublicKey makePublicKey(String stored) throws GeneralSecurityException {
byte[] data = Base64.getDecoder().decode(stored);//Base64.decode(keyBytes, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Enter type of operation:");
String line = scan.nextLine();
if(line.equals("encrypt")){
// Reading from console
System.out.println("Enter name of original ZIP file:");
String originalZipFileName = scan.nextLine();
System.out.println("Enter name of new ZIP file:");
String newZipFileName = scan.nextLine();
System.out.println("Enter name of file containg public key:");
String publicKeyFileName = scan.nextLine();
String publicKey = getPublicKeyString(publicKeyFileName);
// Declaration
ZipFile originalZipFile = new ZipFile(originalZipFileName);
byte[] buffer = new byte[BUFFER_SIZE];
ZipOutputStream newZipFile = new ZipOutputStream(new FileOutputStream(newZipFileName));
Enumeration<? extends ZipEntry> zipEntries = originalZipFile.entries();
//
PublicKey key = makePublicKey(publicKey);
//System.out.println(key.toString());
//
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
while(zipEntries.hasMoreElements()){
ZipEntry entry = zipEntries.nextElement();
ZipEntry copy = new ZipEntry(entry);
newZipFile.putNextEntry(copy);
int read;
InputStream input = originalZipFile.getInputStream(entry);
CipherOutputStream cos = new CipherOutputStream(newZipFile, cipher);
while((read = input.read(buffer)) != -1){
cos.write(buffer, 0, read);
}
input.close();
cos.close();
newZipFile.closeEntry();
}
}
}
}
RSA can only be used to encrypt relatively tiny amounts of data, less the size in bytes of the RSA modulus. When you execute cos.close(), the wrapped cipher object has its doFinal() method called which generates an IllegalBlockSizeException which is silently swallowed by CipherOutputStream. However, since no data made it through the cipher object the ZipOutputStream is messed up, so it throws an exception upon closure.
You can't use RSA the way you are trying to.
I have to do encryption of text file using JCE (Java SE 1.6). For this I have written a method aes256CBCEncrypt which returns CipherOutputstream which I write in file 'encryptedtest'. Now when I am trying to do decryption of this file(named 'encryptedtest') using the method aes256CBCDecrypt, It returns me CipherInputStream which I am writing in 'decryptedtest' to verify its content. Surprisingly, this file is empty.
Can somebody help me out what is wrong with my code.
Code Snippet:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
class MyTest{
public static OutputStream aes256CBCEncrypt(OutputStream os, String passPhrase) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, InvalidKeyException, InvalidAlgorithmParameterException
{
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// md.update(passPhrase.getBytes());
// byte[] key = md.digest();
Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(System.currentTimeMillis());
byte[] bb = new byte[16];
secureRandom.nextBytes(bb);
os.write(bb);
aesCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(passPhrase.getBytes(), "AES"), new IvParameterSpec(
bb));
return new CipherOutputStream(os, aesCipher);
}
public static InputStream aes256CBCDecrypt(File f, String passPhrase)
throws FileNotFoundException
{
FileInputStream fis = null;
try
{
//MessageDigest md = MessageDigest.getInstance("SHA-256");
// md.update(passPhrase.getBytes());
// byte[] key = md.digest();
Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
fis = new FileInputStream(f);
byte[] bb = new byte[16];
fis.read(bb);
aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(passPhrase.getBytes(), "AES"), new IvParameterSpec(
bb));
return new CipherInputStream(fis, aesCipher);
}
catch (final Exception e)
{
}
return null;
}
public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IOException{
String keyFile = "C:\\contentProducer" + File.separator + "test";
String encryptedFile = "C:\\contentProducer" + File.separator + "encryptedtest";
String decryptedFile = "C:\\contentProducer" + File.separator + "decryptedtest";
FileInputStream in = new FileInputStream(keyFile);
FileOutputStream bos = new FileOutputStream(new File(encryptedFile));
//Call method for Encryption
OutputStream encryptedBos = aes256CBCEncrypt(bos,"0123456789abcdef");
int inByte;
while ((inByte = in.read()) != -1 ) {
encryptedBos.write(inByte);
}
in.close();
bos.close();
encryptedBos.close();
//Call Method for Decryption
InputStream inputStream = aes256CBCDecrypt(new File(encryptedFile), "0123456789abcdef");
FileOutputStream deos = new FileOutputStream(new File(decryptedFile));
while ((inByte = inputStream.read()) != -1 ) {
deos.write(inByte);
}
inputStream.close();
deos.close();
}
}
You are closing your FileOutputStream before you close your CipherOutputStream. This prevents the latter from completing its work and writing the encrypted data to disk.
bos.close();
encryptedBos.close();
should change to:
encryptedBos.close();
bos.close();
I do RSA encryption and having a problem. I want to encrypt a string.To convert the string, I already have the rsHex array to convert it.. I run the source code but it give me error say "the system cannot find the file specified" Here is my source code. How do I solve his? Thanks for helping me :)
import de.flexiprovider.api.keys.PrivateKey;
import de.flexiprovider.api.keys.PublicKey;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSA {
private String str, s;
private String chipertext;
private byte[] cipherData;
public RSA(String string) throws Exception {
try {
String input = string;
FileReader read = new FileReader(input);
BufferedReader reader = new BufferedReader(read);
while ((s = reader.readLine()) != null) {
byte[] theByteArray = s.getBytes();
setUserinput(string);
rsHex(theByteArray);
}
} catch (Exception ex) {
Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex);
}
//Creating an RSA key pair in Java
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); //instance of KeyPairGenerator
kpg.initialize(1024);//bit length of the modulus that required
KeyPair kp = kpg.genKeyPair();//returns a KeyPair object
Key publicKey = kp.getPublic(); //pull out the public and private keys
Key privateKey = kp.getPrivate();
//Saving the public and private key
//private key will be placed on our server, and the public key distributed to clients.
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = (RSAPrivateKeySpec) fact.getKeySpec(privateKey, RSAPrivateKeySpec.class);
// Save the file to local drive
saveToFile("c:\\public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("c:\\private.key", priv.getModulus(),priv.getPrivateExponent());
}
private void rsHex(byte[] bytes) throws Exception {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
hex.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
setChipertext(hex.toString());
}
//save the moduli and exponents to file, we can just use boring old serialisation
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
FileOutputStream f = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(f);
oos.writeObject(mod);
oos.writeObject(exp);
oos.close();
}
////Encryption
//initialise the cipher with the public key that we previously saved to file.
PublicKey readKeyFromFile(String keyFileName) throws IOException {
PublicKey key = null;
try {
FileInputStream fin = new FileInputStream(keyFileName);
ObjectInputStream ois = new ObjectInputStream(fin);
BigInteger m = (BigInteger) ois.readObject();
BigInteger e = (BigInteger) ois.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
java.security.PublicKey pubKey = fact.generatePublic(keySpec);
ois.close();
}
catch (Exception e) {
e.printStackTrace();
}
return key;
}
public void rsaEncrypt(String str)throws Exception {
PublicKey pubKey = readKeyFromFile(str);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);//initialise the cipher
cipherData = cipher.doFinal(str.getBytes());//passing in the data to be encrypted
rsHex(cipherData);
}
public String getUserinput() {
return str;
}
public String getChipertext() {
return chipertext;
}
public void setUserinput(String input) {
this.str = input;
}
public void setChipertext(String chipertext) throws Exception {
this.chipertext = chipertext;
}
}
----main Program------
import java.util.Scanner;
public class TWO{
public static void main(String[] args) throws Exception{
Scanner scan = new Scanner(System.in);
System.out.println("Insert your string");
String str = scan.nextLine();
RSA two = new RSA(str);
System.out.println("Encrypted: "+ two.getChipertext());
}
}
The problem is that you're taking an input string from the user, but then your code is treating this as though it was a filename by constructing a FileReader with that string.
Instead of all that nonsense with the FileReader and BufferedReader, is there any reason why you don't just use string.getBytes()?
You also seem to be making life awfully complicated for yourself: you're taking a string, converting into a byte array, then converting that into a string again (with hex representation), then converting that into a byte array again. That's an awful lot of messing about when you could really just take the byte representation of the original string (as given to you by getBytes()) and pass that directly to the RSA encryption.