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.
Related
This question already has answers here:
invalid AES key length error
(4 answers)
Closed 3 years ago.
I want to build App for encrypting and decrypting in java, but shows errors, how can I fix it?
I use AES algorithm for Encrypting and I use java, how can I fix it this code?
This is my code at CryptoException.java
public class CryptoException extends Exception {
public CryptoException() {}
public CryptoException(String message, Throwable throwable) {
super(message, throwable);
}
}
This is My code at CryptoUtils.java
public class CryptoUtils {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES";
public static void encrypt(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public static void decrypt(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private static void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws CryptoException {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error Encrypting/Decrypting file", ex);
}
}
}
And This is my MainApp.java
public class App {
public static void main( String[] args ) {
String key = "Rahasialah";
File inputFile = new File("D:\\document.txt");
File encryptedFile = new File("D:\\document.encrypted");
File decryptedFile = new File("D:\\document.decrypted");
try {
CryptoUtils.encrypt(key, inputFile, encryptedFile);
CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
} catch (CryptoException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
This is my Messages Error:
Error Encrypting/Decrypting file
com.fusi24.bms.EncryptdanDecrypt.CryptoException: Error
Encrypting/Decrypting file
at com.fusi24.bms.EncryptdanDecrypt.CryptoUtils.doCrypto(CryptoUtils.java:53)
at com.fusi24.bms.EncryptdanDecrypt.CryptoUtils.encrypt(CryptoUtils.java:23)
at com.fusi24.bms.EncryptdanDecrypt.App.main(App.java:20)
Caused by: java.security.InvalidKeyException: Invalid AES key length: 10 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:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:863)
at javax.crypto.Cipher.init(Cipher.java:1248)
at javax.crypto.Cipher.init(Cipher.java:1185)
at com.fusi24.bms.EncryptdanDecrypt.CryptoUtils.doCrypto(CryptoUtils.java:36)
... 2 more
You have to use AES encryption in the following way.
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // AES key size in number of bits
SecretKey secKey = generator.generateKey();
The size should be minimum 128 bits as mentioned above.
Then you have to use the following code to encrypt.
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] byteCipherText = aesCipher.doFinal(someTxtToEncrypt.getBytes());
I am trying to encrypt/decrypt using AES-GCM and JDK 1.8 CipherOutputStream, But getting BadPaddingException during decryption. I am using same IV and secret key during encryption and decryption, but not sure what is going wrong. Please see the code below:
static String AES_GCM_MODE = "AES/GCM/NoPadding";
SecretKey secretKey;
public SymmetricFileEncryption(){
Security.insertProviderAt( new BouncyCastleProvider(), 1);
setSecretKey();
}
public static void main(String[] args) throws Exception {
File inputFile = new File("test.txt");
File outputFile = new File("test-crypt.txt");
File out = new File("test-decrypt.txt");
SymmetricFileEncryption sym = new SymmetricFileEncryption();
sym.encrypt(inputFile, outputFile);
sym.decrypt(outputFile, out);
}
public Cipher getEncryptionCipher() throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
Cipher cipher = Cipher.getInstance(AES_GCM_MODE, "BC");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, getInitializationVector());
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(), new IvParameterSpec(getInitializationVector()) );
return cipher;
}
private Cipher getDecryptionCipher(File inputFile) throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException, NoSuchProviderException {
//initialize cipher
Cipher cipher = Cipher.getInstance(AES_GCM_MODE, "BC");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, getInitializationVector());
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(),new IvParameterSpec(getInitializationVector()) );
return cipher;
}
public void encrypt(File inputFile, File outputFile) throws Exception {
Cipher cipher = getEncryptionCipher();
FileOutputStream fos = null;
CipherOutputStream cos = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
cos = new CipherOutputStream(fos, cipher);
byte[] data = new byte[16];
int read = fis.read(data);
while (read != -1) {
cos.write(data, 0, read);
read = fis.read(data);
}
cos.flush();
}catch (Exception e){
e.printStackTrace();
}
finally {
fos.close();
cos.close();
fis.close();
}
String iv = new String(cipher.getIV());
}
public void decrypt(File inputFile, File outputFile) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchProviderException {
Cipher cipher = getDecryptionCipher(inputFile);
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
CipherInputStream cipherInputStream = null;
try{
inputStream = new FileInputStream(inputFile);
cipherInputStream = new CipherInputStream(inputStream, cipher);
outputStream = new FileOutputStream(outputFile);
byte[] data = new byte[16];
int read = cipherInputStream.read(data);
while(read != -1){
outputStream.write(data);
read = cipherInputStream.read(data);
}
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}
finally {
cipherInputStream.close();
inputStream.close();
outputStream.close();
}
}
public void setSecretKey(){
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
secretKey = new SecretKeySpec(key, "AES");
}
public SecretKey getSecretKey(){
return secretKey;
}
public byte[] getInitializationVector(){
String ivstr = "1234567890ab"; //12 bytes
byte[] iv = ivstr.getBytes();//new byte[12];
return iv;
}
Above code results in following error during decryption at line
int read = cipherInputStream.read(data);
javax.crypto.BadPaddingException: mac check in GCM failed
at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:128)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:246)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:222)
at com.rocketsoftware.abr.encryption.SymmetricFileEncryption.decrypt(SymmetricFileEncryption.java:107)
Encryption doesn't work properly: In encrypt, CipherOutputStream#close must be called before FileOutputStream#close. This is because CipherOutputStream#close calls Cipher#doFinal that generates the tag and appends it to the ciphertext. This portion can only be written to the FileOutputStream-instance if FileOutputStream#close has not yet been called. By the way, CipherOutputStream#flush doesn't need to be called.
There is also a problem with decryption: In decrypt, outputStream.write(data) must be replaced by outputStream.write(data, 0, read). Otherwise usually too much data will be written to the FileOutputStream-instance.
The classes javax.crypto.CipherInputStream and javax.crypto.CipherOutputStream may perform the authentication false positive and are therefore not suitable for GCM-mode, e.g. from the documentation (Java 12) for CipherInputStream:
This class may catch BadPaddingException and other exceptions thrown by failed integrity checks during decryption. These exceptions are not re-thrown, so the client may not be informed that integrity checks failed. Because of this behavior, this class may not be suitable for use with decryption in an authenticated mode of operation (e.g. GCM). Applications that require authenticated encryption can use the Cipher API directly as an alternative to using this class.
Therefore, either the Cipher API should be used directly, as recommended in the documentation, or the BouncyCastle-implementations org.bouncycastle.crypto.io.CipherInputStream and org.bouncycastle.crypto.io.CipherOutputStream, e.g. for encryption:
import org.bouncycastle.crypto.io.CipherInputStream;
import org.bouncycastle.crypto.io.CipherOutputStream;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.AEADBlockCipher;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;
...
public void encrypt(File inputFile, File outputFile) throws Exception {
AEADBlockCipher cipher = getEncryptionCipher();
// Following code as before (but with fixes described above)
...
}
public AEADBlockCipher getEncryptionCipher() throws Exception {
AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
cipher.init(true, // encryption
new AEADParameters(
new KeyParameter(getSecretKey().getEncoded()),
128, // tag length
getInitializationVector(),
"Optional Associated Data".getBytes()));
return cipher;
}
...
and analog for decryption.
Note that even if authentication fails, decryption is performed, so the developer must ensure that the result is discarded and not used in this case.
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.");
}
}
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();
I'm doing a simple encryption file transfer system and now stopped by a run time exception:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at ftpclient.FTPClient.main(FTPClient.java:82)
I tried to debug my code using a string to encrypt and decrypt with the same key and it works. However, when I tried to transfer stream from the file, this exception always comes.
Here are the codes of both sides. At first they will exchange symmetric key (AES key) via RSA and then transfer large files via AES encryption. We can focus on the last part of each code where the files are encrypted and decrypted by AES key.
Server Side:
package ftpserver;
import java.io.*;
import java.net.*;
import javax.crypto.*;
import java.security.*;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* #author Han
*/
public class FTPServer {
public static void main(String[] args) throws Exception {
//generate symmetric key and initialize cipher for AES
SecretKey skey = null;
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
skey = kg.generateKey();
//get public key of the receive side
final String PUBLIC_KEY_PATH = "key_b.public";
PublicKey publickey = null;
try {
FileInputStream fis;
fis = new FileInputStream(PUBLIC_KEY_PATH);
ObjectInputStream oin = new ObjectInputStream(fis);
publickey = (PublicKey) oin.readObject();
oin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
};
//encrypte symmetric key with own private key and send out
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, publickey);
byte cipherSKey[] = rsa.doFinal(skey.getEncoded());
//System.out.println(skey); //debug
//create tcp server socket
ServerSocket tcp = new ServerSocket(2000);
Socket client = tcp.accept();
//get input&output stream from the TCP connection
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//generate a file input stream to get stream from file
File sentFile = new File("F:\\test.txt");
FileInputStream fin = new FileInputStream(sentFile);
//send encrypted symmetric key first
out.write("Symmetric Key:\r\n".getBytes());
out.write(cipherSKey);
DataInputStream din = new DataInputStream(in);
while(true)
{
if(din.readLine().equals("Received."))
{
System.out.println("Send key successfully.");
break;
}
};
//send files
int count;
byte[] bytearray = new byte[8192];
byte[] cipherbuffer;
while((count = fin.read(bytearray))>0)
{
cipherbuffer = Base64.encodeBase64(aes.doFinal(bytearray));
out.write(cipherbuffer,0,cipherbuffer.length);
System.out.println(count+" bytes have been sent.");
};
out.flush();
out.close();
client.close();
}
}
Client Side:
package ftpclient;
import java.io.*;
import java.net.*;
import java.security.PrivateKey;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* #author Han
*/
public class FTPClient {
public static void main(String[] args) throws Exception
{
//get the private key of this side
final String PUBLIC_KEY_PATH = "key_b.privat";
PrivateKey privatkey = null;
try {
FileInputStream fis;
fis = new FileInputStream(PUBLIC_KEY_PATH);
ObjectInputStream oin = new ObjectInputStream(fis);
privatkey = (PrivateKey) oin.readObject();
oin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
};
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, privatkey);
//create tcp client socket
Socket tcp = new Socket("192.168.1.185",2000);
InputStream in = tcp.getInputStream();
OutputStream out = tcp.getOutputStream();
DataInputStream din = new DataInputStream(in);
//receive symmetric key from server
byte keybuffer[] = new byte[128];
SecretKey skey = null;
while(true)
{
if(din.readLine().equals("Symmetric Key:"))
{
System.out.println("Start to receiving key...");
in.read(keybuffer);
byte[] skeycode = rsa.doFinal(keybuffer);
skey = new SecretKeySpec(skeycode, 0, skeycode.length, "AES");
out.write("Received.\r\n".getBytes());
break;
}
};
//create cipher for symmetric decryption
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.DECRYPT_MODE, skey);
//System.out.println(skey); //debug
//create file stream
FileOutputStream fos = new FileOutputStream("E:\\test_cp.txt");
int count;
int i = 0;
byte[] bytearray = new byte[8192];
byte[] buffer;
while((count = in.read(bytearray)) > 0)
{
buffer = (aes.doFinal(Base64.decodeBase64(bytearray)));
fos.write(buffer,0,buffer.length);
i +=count;
System.out.println(i+" bytes have been received.");
};
fos.flush();
fos.close();
in.close();
tcp.close();
System.out.println("File Transfer completed");
}
}
you are calling doFinal multiple times. or at least trying to.
when you read data, not all data arrives or is read into the buffer at once. so you decrypt some and then read again. that is all ok.
but when you do that, you are calling doFinal each time, instead of update. this is wrong and is the cause of the error. instead, replace doFinal with update and then add an extra doFinal once you have finished reading all data (there is a doFinal() that takes no arguments for exactly this reason).
see http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html
also see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29 for why ecb mode is often not a good idea (look at the penguin pictures).