Transfer Multiple File problems via socket - java

Server side:
public class Server
{
public static final String ALGORITHM = "RSA";
public static final String PRIVATE_KEY_FILE = "C:/Users/mrarsenal10/Desktop/server/key/private.key";
public static final String PUBLIC_KEY_FILE = "C:/Users/mrarsenal10/Desktop/server/key/public.key";
public static void generateKey()
{
try
{
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
public static boolean areKeysPresent()
{
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists())
{
return true;
}
return false;
}
public static String decrypt(byte[] text, PrivateKey key) { // giải mã
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
static void sendFile(Socket sock, String fName) throws FileNotFoundException, IOException
{
File transferFile = new File (fName);
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length); // luu vao bytearray
OutputStream os = sock.getOutputStream(); // goi outputstream de
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
if (!areKeysPresent()) {
generateKey();
}
ServerSocket serverSocket = new ServerSocket(15124);
Socket sock = serverSocket.accept();
sendFile(sock, PUBLIC_KEY_FILE);
sendFile(sock, "lich.txt");
sock.close();
}
}
Client side:
public class Client
{
public static final String ALGORITHM = "RSA";
public static final String PUBLIC_KEY_FILE = "C:/Users/mrarsenal10/Desktop/Client/public.key";
static void recvFile(Socket sock, String fName) throws FileNotFoundException, IOException
{
int filesize=1022386;
int bytesRead;
int currentTot = 0;
byte [] bytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead; }
while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
}
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Socket sock = new Socket("127.0.0.1",15124);
recvFile(sock, "public.key");
recvFile(sock, "lich.txt");
sock.close();
}
}
My problem is here i just can send "public.key" or "lich.txt" from server to client, now i want to send both "public.key" and "lich.txt". Thank for your help.

The problem is with the overall design of both the Server and the Client. On the server side it is sending two different files, but on the Client side it is just a stream of data. There is no distinction between one byte representing data from one file vs the next. So what is probably happening is you are calling recvFile, which receives ALL the data from BOTH files sent by the server. After sending the data, the server closes the connection. (You do this explicitly.) So now, on the client side, you have an invalid socket. However, you try to call recvFile again with the socket thinking that represents the second file. This will lead to the SocketException or more likely OutOfBoundsException you are seeing.
To fix this, you need to add more hand-shaking between the Server and Client. The simplest would be a delimiter representing the end of a file. A better approach would be to append a known-size header to the front of every "message" (aka file) before sending any data which lets the client know the size of the file. Then once the client receives the header it knows exactly how many bytes to read.
For now, to prevent the crash change you're recvFile method to something like this:
byte[] bytearray = new byte[4096];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
int bytesRead;
while ((bytesRead = is.read(bytearray)) >= 0) {
if (bytesRead > 0) {
fos.write(bytearray, 0, bytesRead);
}
}
fos.flush();
fos.close();

Related

Getting errors when trying to decrypt a file

package test;
/**
* Created by
* newbme on 12/25/2018.
*/
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class MyJava {
/**
* IT IS THIS CLASS THAT WILL ENCRYPT OR DECRYPT
* ANY FILE
*/
private static final String SECRET_KEY_1 = "ssdkF$HUy2A#D%kd";
private static final String SECRET_KEY_2 = "weJiSEvR5yAC5ftB";
private IvParameterSpec ivParameterSpec;
private SecretKeySpec secretKeySpec;
private Cipher cipher;
private File from,to;
private static boolean trouble =false;
/**
* CBC MODE
*/
public MyJava(File from,File to) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes("UTF-8"));
secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
//INITIALIZE THE PLACE TO READ AND SAVE FILE
this.from =from;
this.to =to;
//if the desination doesnt exists create it
if(! this.to .exists()){
try {
this.to.getParentFile().mkdirs();
this.to.createNewFile();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
/**
*
* USE THIS METHOD TO ENCRYPT ANYTHING
*/
public boolean encrypt()throws Exception{
FileInputStream fis =null;
FileOutputStream fos=null;
boolean success =false;
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
//read the file into memory
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
byte [] inBytes = new byte[50*1024];
int count;
while( ( count = fis.read(inBytes)) > 0){
byte encrypted[] = cipher.doFinal(inBytes);
fos.write(encrypted,0,count);
fos.flush();
}
success =true;
}catch(InvalidKeyException ivke){
ivke.printStackTrace();
trouble = true;
}finally{
if(fis!=null)fis.close();
if(fos!=null)fos.close();
}
//return Base64.encodeBase64String(encrypted);
return success;
}
/**
*
* USE THIS METHOD TO DECRYPT ANYTHING
*/
public boolean decrypt() throws Exception{
FileInputStream fis =null;
FileOutputStream fos=null;
boolean success =false;
try {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
//read the file into memory
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
byte [] inBytes = new byte[50*1024];
int count;
while( ( count = fis.read(inBytes)) > 0){
byte decrypted[] = cipher.doFinal(inBytes);//this line fails
fos.write(decrypted,0,count);
fos.flush();
}
success =true;
}catch(InvalidKeyException ivke){
trouble = true;
ivke.printStackTrace();
}finally{
if(fis!=null)fis.close();
if(fos!=null)fos.close();
}
//return Base64.encodeBase64String(encrypted);
return success;
}
private static boolean isInvalidKeyException(){
return trouble;
}
public static void main(String [] R){
File f = new File(PATH);
//encrypt
new MyJava(f,new File("c:/logs1/"+f.getName())).encrypt();
//Toast.makeText(context,"to decrypt",Toast.LENGTH_LONG).show();
//decrypt
new MyJava(f,new File("c:/logs2/"+f.getName())).decrypt();
}
}
Error:
D/OpenSSLLib: OpensslErr:Module:30(101:); file:external/boringssl/src/crypto/cipher/cipher.c ;Line:460;Function:EVP_DecryptFinal_ex
W/System.err: javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
W/System.err: at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
W/System.err: at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:568)
W/System.err: at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:350)
W/System.err: at javax.crypto.Cipher.doFinal(Cipher.java:2056)
W/System.err: at com.presentapps.aiapp.utility.AISCipher.decrypt(AISCipher.java:122)
W/System.err: at com.presentapps.aiapp.popups.ActionPop$1.onClick(ActionPop.java:65)
Hello, I tried to encrypt a file which could be a text file or a music file etc. The program kinda encrypts it without any exception, however when I try to decrypt, it throws an exception.
I've been trying to use CBC mode to get it working for days now, could someone help point out my errors?
And uhm, I am actually running it on Android device so I changed the root part with "c:" while posting on SO the error posted was same gotten from debugger console on A.S.
I'm a newb to java, just improving on my learning, so any help is appreciated. Thanks.
Please note that real code should use a non-secret random IV for each encryption rather than a fixed, secret IV. Passwords should use a password-hashing function to make into keys. PBKDF2 is available on Android and Java for this purpose.
There are a number of problems with your code:
You're calling Cipher.doFinal() every time through the loop. Combined with a fixed IV, the result is effectively equivalent to ECB mode and is thus insecure. Use Cipher.update() for all intermediate blocks until the final block, then call Cipher.doFinal().
You're supplying invalid data to encrypt and decrypt every time you read less than a full buffer into inBytes.
count is the number of bytes that were read in, not necessarily the size of encrypted. You should output exactly the contents of encrypted, not some piece of it.
You main method encrypts a file at PATH and writes the result to c:/logs1/PATH. It then attempts to decrypt the file at PATH, but that file is the plaintext file, not the cipher text file.
Here are the corrected encrypt and decrypt methods:
public boolean encrypt() throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
boolean success = false;
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
//read the file into memory
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
byte[] inBytes = new byte[50 * 1024];
int count;
while ((count = fis.read(inBytes)) > 0) {
byte encrypted[] = cipher.update(inBytes, 0, count);
fos.write(encrypted);
}
byte encrypted[] = cipher.doFinal();
fos.write(encrypted);
fos.flush(); // redundant, since closing the stream will flush it.
success = true;
} catch (InvalidKeyException ivke) {
ivke.printStackTrace();
trouble = true;
} finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
//return Base64.encodeBase64String(encrypted);
return success;
}
public boolean decrypt() throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
boolean success = false;
try {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
//read the file into memory
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
byte[] inBytes = new byte[50 * 1024];
int count;
while ((count = fis.read(inBytes)) > 0) {
byte decrypted[] = cipher.update(inBytes, 0, count);
fos.write(decrypted);
}
byte decrypted[] = cipher.doFinal();
fos.write(decrypted);
fos.flush();
success = true;
} catch (InvalidKeyException ivke) {
trouble = true;
ivke.printStackTrace();
} finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
//return Base64.encodeBase64String(encrypted);
return success;
}

How to use PipedInputStream and PipedOutputStream

There are many examples of using while converting OutputStream to InputStream.
How could I complete the missing parts below?
I mean putDataOnOutputStream(out) method.
If it is still needed to use ByteArrays, in this case, it doesn't make sense what is the memory advantage of using PipeLines
I need to complete convertToInputStream ;
public static InputStream decrypt(String keyCode, String file) throws IOException, InterruptedException {
OutputStream out;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/Pkcs5Padding");
/****** decyption code
**/
out = new BufferedOutputStream(new FileOutputStream("C:decyrptedText.txt"));
for(int readBytes = in.read(buffer); readBytes>-1; readBytes = in.read(buffer)) {
byte[] decrypted = cipher.update(buffer, 0, readBytes);
out.write(decrypted);
}
byte[] decrypted = cipher.doFinal();
out.write(decrypted);
out.flush();
out.close();
in.close();
} catch (Exception e) {
throw new IllegalStateException(e);
}
return convertToInputStream(out); //
}
public static InputStream convertToInputStream(OutputStream outputStream) throws IOException, InterruptedException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
new Thread(
new Runnable(){
public void run(){
//put your code that writes data to the outputstream here.
putDataOnOutputStream(outputStream);
}
}
).start();
//data can be read from the pipedInputStream here.
processDataFromInputStream(in);

Given final block not properly padded exception

I have Server-Client sockets to send byte-array from client to server, I am trying to use Cipher Input Stream, Cipher output Stream but I am getting the following exception:
javax.crypto.BadPaddingException: Given final block not properly
padded. Exception in thread "main" java.io.IOException:
javax.crypto.BadPaddingException: Given final block not properly
padded at
javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:121) at
javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:121)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:239)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:215)
at SecretSocketServer.main(SecretSocketServer.java:46) Caused by:
javax.crypto.BadPaddingException: Given final block not properly
padded at
com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966) at
com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824) at
com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2048) at
javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:118)
I tried different algorithm than "DES" but still getting the same exception
this is my code:
public class SecretSocket {
Cipher inCipher, outCipher;
Socket socket;
Key key;
public SecretSocket(Socket socket, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
this.key = key;
this.socket = socket;
initializeCipher();
}
private void initializeCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
outCipher = Cipher.getInstance("DES");
outCipher.init(Cipher.ENCRYPT_MODE, key);
inCipher = Cipher.getInstance("DES");
inCipher.init(Cipher.DECRYPT_MODE, key);
}
public InputStream getInputStream() throws IOException {
InputStream is = socket.getInputStream();
CipherInputStream cis = new CipherInputStream(is, inCipher);
return cis;
}
public OutputStream getOutputStream() throws IOException {
OutputStream os = socket.getOutputStream();
CipherOutputStream cos = new CipherOutputStream(os, outCipher);
return cos;
}
}
public class KeyGen {
public static void writeKey() throws NoSuchAlgorithmException, FileNotFoundException, IOException {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
File file = new File("key1.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key);
}
public class SecretSocketServer {
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
int port = 12345;
ServerSocket Serversocket;
Socket clientSocket;
Serversocket = new ServerSocket(port);
System.out.println("Waiting for client to connect");
clientSocket = Serversocket.accept();
System.out.println("New Client Connected");
Key key = KeyGen.getSecretKey();
System.out.println("The Key is: " + key);
SecretSocket s = new SecretSocket(clientSocket, key);
InputStream in = s.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int numberOfBytedRead;
while ((numberOfBytedRead = in.read(b)) >= 0) {
baos.write(b, 0, numberOfBytedRead);
}
System.out.println(new String(baos.toByteArray()));
Serversocket.close();
}
}
public static final String KEY_FILE = "key1.txt";
public static Key getSecretKey() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(KEY_FILE);
ObjectInputStream ois = new ObjectInputStream(fis);
Key key = (Key) ois.readObject();
return key;
}
public class SecretSocketClient {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, ClassNotFoundException, NoSuchPaddingException, InvalidKeyException {
int port = 12345;
Socket soc = new Socket("localhost", port);
System.out.println("Connected to server");
KeyGen.writeKey();
Key key = KeyGen.getSecretKey();
System.out.println("Key Generated: " + key);
SecretSocket s = new SecretSocket(soc, key);
//InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
out.write("HELLOWORLD".getBytes());
out.flush();
out.close();
soc.close();
System.out.println("The MSG has been sent");
}
}
There are many things that can cause a "Bad Padding" exception. Basically anything that causes the end of the last block not to match the expected padding will throw the error. Possible causes include: incorrect padding setting, incorrect key, corrupted cyphertext and others.
To try and diagnose the problem, set the decryption side to NoPadding. This will accept anything, and allow you to examine the output:
complete garbage: you probably have an error in the key or the wrong mode setting.
first block garbage: you may have a key error or an IV error.
last block garbage: likely a corrupt end to the cyphertext file.
a correct decryption with some strange bytes at the end: the strange bytes are the padding.
If it really is just the padding, then set the decryption function to expect that sort of padding. Otherwise check that the key/IV/cyphertext are byte-for-byte the same for both encryption and decryption.
It is vital that you set a padding mode after diagnosis. NoPadding is insecure.

javax.crypto.BadPaddingException: Decryption error

Here is the error I have got when run my Encode & Decode Class.
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:64)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
java.lang.NullPointerException
at java.lang.String.<init>(String.java:556)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:70)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
Here is the source code of RSAEncDecDemo.java class file.
public class RSAEncDecDemo {
private static final String PUBLIC_KEY_FILE = "lk.public.key";
private static final String PRIVATE_KEY_FILE = "lk.private.key";
#SuppressWarnings("restriction")
public static void main(String[] args) throws IOException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
writeStringkey(PUBLIC_KEY_FILE,new BASE64Encoder().encode(publicKey.getEncoded()));
writeStringkey(PRIVATE_KEY_FILE,new BASE64Encoder().encode(privateKey.getEncoded()));
String demoString = "123346";
RSAEncDecDemo rsa = new RSAEncDecDemo();
String decrypted = rsa.decryptData(demoString);
String msisdn = decrypted.substring(0,decrypted.indexOf("|"));
} catch (Exception e) {
e.printStackTrace();
}
}
private String decryptData(String strData) throws IOException {
byte[] data = DatatypeConverter.parseHexBinary(strData);
byte[] descryptedData = null;
try {
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return new String(descryptedData);
}
#SuppressWarnings("restriction")
public PrivateKey readPrivateKeyFromFile(String fileName)throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {
String publicK = readStringKey(fileName);
byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePrivate(keySpec);
}
public PrivateKey readPrivateKeyFromFileold(String fileName)throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
if (fis != null) {
fis.close();
}
}
}
return null;
}
public static void writeStringkey(String fileName, String data) {
try {
FileWriter out = new FileWriter(new File(fileName));
out.write(data);
out.close();
} catch (IOException e) {
}
}
public static String readStringKey(String fileName) {
BufferedReader reader = null;
StringBuffer fileData = null;
try {
fileData = new StringBuffer(2048);
reader = new BufferedReader(new FileReader(fileName));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (Exception e) {
} finally {
if (reader != null) {
reader = null;
}
}
return fileData.toString();
}
}
Where is mistaken point.? Decryption part is give that error.
Whole class uploaded here
LINK TO SOURCE CODE
-Thanks
In principle a ciphertext should be indistinguishable from random. That said, ciphers do place constraints on the domain (size and possible values). In the case of RSA PKCS#1 - which is the default mode for "RSA" within the Oracle provider - the output must be precisely the key size (in bytes). Furthermore, the value must be smaller than the modulus.
Now assume that you've just shown us a demo value (because the exception doesn't match the input) and the size of the ciphertext is correct. In that case you would get an unpadding exception when either:
the private key doesn't match the public key used;
the wrong padding mode (e.g. OAEP) was used to create the ciphertext;
the ciphertext was altered (e.g. due to an invalid conversion to a string).
You would have to try until you find the culprit, without the required information we cannot test this for you.

Not able to transfer AES encrypted file through socket programming

I'm trying to transfer an AES encrypted file through socket programming, but when I specify the file path it gives the following exception, and when I try to transfer an unencrypted file, it works fine.
java.io.FileNotFoundException: salt.ecn (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at nigam.Front.server(Front.java:52)
at nigam.Front$7.run(Front.java:621)
Code:
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("salt.ecn");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("C:\\Users\\SIDDHARTH\\Documents\\NetBeansProjects\\Nigam\\salt.ecn");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}
'Code: Encryption code used'
Code: Encryption code used
public class AESFileEncryption {
public static void main(String[] args) throws Exception {
// file to be encrypted
FileInputStream inFile = new FileInputStream("plainfile.txt");
// encrypted file
FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
// password to encrypt the file
String password = "javapapers";
// password, iv and salt should be transferred to the other end
// in a secure manner
// salt is used for encoding
// writing it to a file
// salt should be transferred to the recipient securely
// for decryption
byte[] salt = new byte[8];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
FileOutputStream saltOutFile = new FileOutputStream("salt.enc");
saltOutFile.write(salt);
saltOutFile.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
256);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
// iv adds randomness to the text and just makes the mechanism more
// secure
// used while initializing the cipher
// file to store the iv
FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ivOutFile.write(iv);
ivOutFile.close();
//file encryption
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outFile.write(output);
inFile.close();
outFile.flush();
outFile.close();
System.out.println("File Encrypted.");
}
}

Categories

Resources