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.");
}
}
Related
Ok guys ! There is my trouble.
I want to read data from an encrypted file and store the decrypted data in a local variable (without save it in a file).
So, when I do the operations (in the same Class) cryptingFile -> DecryptFile -> Storage : It's OK.
But, when I try to run again the code using the crypted file directly, I've got the error "BadPaddingException".
I've no idea what's going on....
Below, the working code:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
generateKey(clef);
CryptingWithSave(Cipher.ENCRYPT_MODE,"db/db.csv",publicKey,"db/db.csv_encrypted");
decrypt_file("db/db.csv_encrypted",publicKey);
System.out.println(tab);
}
public static void generateKey (String clef) throws NoSuchAlgorithmException{
final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
final SecretKey key = keyGen.generateKey();
publicKey= new SecretKeySpec(key.getEncoded(),"AES");
}
public static void CryptingWithSave (int Crypting_METHOD,String inputFile, SecretKeySpec clef, String outputFile) throws NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, Exception{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Crypting_METHOD, clef);
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
fos.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
fos.close();
}
public static void decrypt_file (String inputFile, SecretKeySpec clef) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher2 = Cipher.getInstance("AES");
cipher2.init(Cipher.DECRYPT_MODE, clef);
FileInputStream fis = new FileInputStream(inputFile);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(input)) != -1) {
byte[] output = cipher2.update(input, 0, bytesRead);
if (output != null)
tab=tab.concat(new String(output));
}
byte[] output = cipher2.doFinal();
if (output != null)
tab=tab.concat(new String(output));
fis.close();
}
There, the unworking code (the only change is the CryptingWithSave which is commented):
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
generateKey(clef);
//CryptingWithSave(Cipher.ENCRYPT_MODE,"db/db.csv",publicKey,"db/db.csv_encrypted");
decrypt_file("db/db.csv_encrypted",publicKey);
System.out.println(tab);
}
public static void generateKey (String clef) throws NoSuchAlgorithmException{
final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
final SecretKey key = keyGen.generateKey();
publicKey= new SecretKeySpec(key.getEncoded(),"AES");
}
public static void CryptingWithSave (int Crypting_METHOD,String inputFile, SecretKeySpec clef, String outputFile) throws NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, Exception{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Crypting_METHOD, clef);
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
fos.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
fos.close();
}
public static void decrypt_file (String inputFile, SecretKeySpec clef) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher2 = Cipher.getInstance("AES");
cipher2.init(Cipher.DECRYPT_MODE, clef);
FileInputStream fis = new FileInputStream(inputFile);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(input)) != -1) {
byte[] output = cipher2.update(input, 0, bytesRead);
if (output != null)
tab=tab.concat(new String(output));
}
byte[] output = cipher2.doFinal();
if (output != null)
tab=tab.concat(new String(output));
fis.close();
}
It is because the next time you run it, it generates a new key which is different from the previous one. Try to use that old key.
Hi i hav such code that encrypt and decrypt file in DES algorithm .
i want to change my code to be triple DES encryption / decryption .
my code is below :
First, my methods are :
public class DESEncrypt
{
public static void encrypt(String key, InputStream is, OutputStream os) throws Exception {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Exception {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Exception {
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);
makeFile(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
makeFile(is, cos);
}
}
public static void makeFile(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();
}
}
public class EncryptTXT extends javax.swing.JFrame {
String key="Java#123##"; //This is the Key for Encryption
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(null);
String path=fc.getSelectedFile().getAbsolutePath();
jLabel2.setText(path);
File f=fc.getSelectedFile();
FileInputStream fis=new FileInputStream(f);
FileOutputStream fos=new FileOutputStream("C:/Users/user/Desktop/encrypted.txt");
Thread.sleep(2000);
DESEncrypt.encrypt(key, fis, fos);
jLabel4.setText("C:/Users/user/Desktop/encrypted.txt");
The 3DES keys should be 16 or 24 bytes long, not 8.
Change "DES" to "DESede" as Maarten Bodewes suggested or "DESede\ECB\NoPadding" (in .getInstance() method)
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 using CipherInputStream and CipherOutputStream to encrypt files using AES.
encrypt(...) seems to be working fine, but my decrypt(...) function only decrypt the first 16 bytes of my files.
Here is my class :
public class AESFiles {
private byte[] getKeyBytes(final byte[] key) throws Exception {
byte[] keyBytes = new byte[16];
System.arraycopy(key, 0, keyBytes, 0, Math.min(key.length, keyBytes.length));
return keyBytes;
}
public Cipher getCipherEncrypt(final byte[] key) throws Exception {
byte[] keyBytes = getKeyBytes(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher;
}
public Cipher getCipherDecrypt(byte[] key) throws Exception {
byte[] keyBytes = getKeyBytes(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher;
}
public void encrypt(File inputFile, File outputFile, byte[] key) throws Exception {
Cipher cipher = getCipherEncrypt(key);
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[1024];
int read = fis.read(data);
while (read != -1) {
cos.write(data, 0, read);
read = fis.read(data);
System.out.println(new String(data, "UTF-8").trim());
}
cos.flush();
} finally {
fos.close();
cos.close();
fis.close();
}
}
public void decrypt(File inputFile, File outputFile, byte[] key) throws Exception {
Cipher cipher = getCipherDecrypt(key);
FileOutputStream fos = null;
CipherInputStream cis = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(outputFile);
byte[] data = new byte[1024];
int read = cis.read(data);
while (read != -1) {
fos.write(data, 0, read);
read = cis.read(data);
System.out.println(new String(data, "UTF-8").trim());
}
} finally {
fos.close();
cis.close();
fis.close();
}
}
public static void main(String args[]) throws Exception {
byte[] key = "mykey".getBytes("UTF-8");
new AESFiles().encrypt(new File("C:\\Tests\\secure.txt"), new File("C:\\Tests\\secure.txt.aes"), key);
new AESFiles().decrypt(new File("C:\\Tests\\secure.txt.aes"), new File("C:\\Tests\\secure.txt.1"), key);
}
}
So my question is, why the decrypt function only read the first 16 bytes ?
This is very subtle. Your problem is that you are closing your fos before your cos. In your encrypt(...) method you are doing:
} finally {
fos.close();
cos.close();
fis.close();
}
That closes the FileOutputStream out from under the CipherOutputStream so the final padded block of encrypted output never gets written to the output file. If you close the fos after the cos then your code should work fine.
Really, you should consider doing something like:
FileOutputStream fos = null;
CipherOutputStream cos = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
cos = new CipherOutputStream(fos, cipher);
// once cos wraps the fos, you should set it to null
fos = null;
...
} finally {
if (cos != null) {
cos.close();
}
if (fos != null) {
fos.close();
}
if (fis != null) {
fis.close();
}
}
FYI: org.apache.commons.io.IOUtils has a great closeQuietly(...) method which handles null checks and catches the exceptions for you.
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) {
}
}
}
}