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);
Related
I used to AES-128 CBC with NoPadding algorithm according to Apple's Technical Note. I can encrypt and decrypt any video with following code below. I tried Muxed encrypted and Un-Muxed encrypted video both. But i couldnt decrypt original test contents properly. When i encrypt original unencrypted files it doesnt play on Safari.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Main {
public static void main(String[] args)
throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchPaddingException, FileNotFoundException, IllegalBlockSizeException, BadPaddingException, IOException {
// TODO Auto-generated method stub
byte[] IVBytes = "\u00d5\u00fb\u00d6\u00b8\u002e\u00d9\u003e\u004e\u00f9\u008a\u00e4\u0009\u0031\u00ee\u0033\u00b7".getBytes();
byte[] KeyBytes = "\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c".getBytes();
IvParameterSpec ivspec = new IvParameterSpec(IVBytes);
SecretKeySpec skey = new SecretKeySpec(KeyBytes, "AES");
Cipher ci = Cipher.getInstance("AES/CBC/NoPadding");
ci.init(Cipher.DECRYPT_MODE, skey, ivspec);
processFile(ci, "C:\\test_java\\encryted.ts", "C:\\test_java\\unencryted.ts");
/*
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
processFile(ci, "C:\\test_java\\main.ts", "C:\\test_java\\encrypted_unmu.ts");
*/
}
static private void processFile(Cipher ci, String inFile, String outFile)
throws FileNotFoundException, IOException, IllegalBlockSizeException, BadPaddingException {
try (FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile)) {
byte[] ibuf = new byte[1024];
int len;
while ((len = in.read(ibuf)) != -1) {
len = len - (len % 16);
byte[] obuf = ci.update(ibuf, 0, len);
if ( obuf != null ) out.write(obuf);
}
byte[] obuf = ci.doFinal();
if ( obuf != null ) out.write(obuf);
}
}
}
I developed a java application as follows such that it reads public key from PEM file and then verifies the signature. I received this signature from the outside (a company) and it has been generated using RSA2048. However I receive following error message:
"Signature length not correct: got 384 but was expecting 256."
Must I do some modification on this signature before verification?
package read_key_pck;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main {
//protected final static Logger LOGGER = Logger.getLogger(Main.class);
public final static String RESOURCES_DIR = "C:\\Users\\KX5710\\eclipse-workspace\\read_key\\src\\read_key_pck\\";
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
PublicKey pub = null;
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
/*PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
+ "id_rsa");*/
pub = generatePublicKey(factory, RESOURCES_DIR
+ "rsa_2048_pub.pem");
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
String encodedPublicKey = Base64.getEncoder().encodeToString(pub.getEncoded());
System.out.println("publickey: " + encodedPublicKey);
boolean isCorrect = verify(" 5 5.00 1.80", "12c1d454cde1c3ca07f179fc3c8d1e739b482b0447cd2c60342455a10db15ee8657e73e7f9195f7e33d93db8fc1cda236d41bf2a804be0f860c16ebf952c02e89f254a19daf54b66d1383ebe5aaf049e7c48ecd33a98f771165cb8b7b0323d81508c6260109c8f622655f363bbf638802d92c985e8ab982eebc7167c979cde4755b7afcc880e32118c3e6b72eecbd0ebf680da84a59c8cc523051c3a8ec12595ec6bdc0856b9faf9562919c315e78655c8f35f759899f27d729e56a96ec8bd85fe6221441dd91f9facd5f5eadcb4b7fac08a9ddab29f18d353e6762e0769068077fea7bc94d6df405a86c9e98096e8e50e59ec7263ce6c4e88bb96ab3c663baa", pub);
System.out.println("Signature verification: " + isCorrect);
}
private static PublicKey generatePublicKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return factory.generatePublic(pubKeySpec);
}
}
package read_key_pck;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class PemFile {
private PemObject pemObject;
public PemFile(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
Your signature is encoded as HEX not as BASE64.
Change
byte[] signatureBytes = Base64.getDecoder().decode(signature);
with
byte[] signatureBytes = DatatypeConverter.parseHexBinary(signature)
I've encoded a simple json data using RSA public key and now I'm trying to decode it. The encoding part was done via terminal and the decoding is being performed programmatically. To verify the integrity of the encrypted file, I decrypted it via terminal and it works just fine. Now that I'm trying to decrypt the file programmatically, I'm running into decrypting issues. I can read the private_key.pem file perfectly and pass it to Cipher for decrypting the encoded file, however upon doing this I get the following exception.
java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block
at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.CipherSpi.engineDoFinal(CipherSpi.java:457)
at javax.crypto.Cipher.doFinal(Cipher.java:1204)
at com.benchmark.openssl.RSADecryption.decipherString(RSADecryption.java:295)
at com.benchmark.openssl.RSADecryption.main(RSADecryption.java:263)
at com.benchmark.MainActivity$1.onComplete(MainActivity.java:157)
at io.reactivex.internal.operators.completable.CompletableObserveOn$ObserveOnCompletableObserver.run(CompletableObserveOn.java:90)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:463)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
OpenSSL Commands used:
openssl genrsa -out priv_key.pem 2048
openssl rsa -pubout -in priv_key.pem -out pub_key.pem
openssl rsautl -encrypt -in userdata.json -out user_encrypted_with_pub_key -inkey pub_key.pem –pubin
openssl rsautl -decrypt -in user_encrypted_with_pub_key -inkey priv_key.pem --> This is what I'm trying to do programmatically.
Code:
import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemReader;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public static void main(String privateKeyPath, String encodedFilePath) throws FileNotFoundException,
IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
String encodedString = readFileAsString(encodedStringPath);
Timber.v("Encoded String: %s", encodedString);
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
PrivateKey priv = generatePrivateKey(factory, privateKeyPath);
Timber.i(String.format("Instantiated private key: %s", priv));
decipherString(priv, encodedString);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename, false);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
private static void decipherString(PrivateKey privateKey, String encodedStringData) {
byte[] dectyptedText = null;
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
dectyptedText = cipher.doFinal(encodedStringData.getBytes()); <---- EXCEPTION HERE
Timber.w("Deciphered text is: %s", new String(dectyptedText));
}
catch (Exception e) {
e.printStackTrace();
}
}
static class PemFile {
private PemObject pemObject;
public PemFile(String filename, boolean isBase64) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
userdata.json:
{
"username":"umer",
"password":"123456",
"pin" : "123"
}
I figured it out by some trial and error since I don't have much knowledge about openssl. Anyways the process for decrypting an encrypted file should be the following.
Terminal:
String -> (Encrypt) -> Encrypted String -> (convert to base64) -> EncryptedBase64EncodedString -> (Decrypt) -> Original String
Programmtically:
EncryptedBase64EncodedString -> (convert from base64 to normal string [Use Default parameters only! No Padding or other constants for decoding base64 string]) -> Pass private_key & decoded string to Cipher -> Profit.
The resultant code is:
import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemReader;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public static void main(String privateKeyPath, String publicKeyPath, String encodedStringPath, boolean isPublicKeyAndDataBase64) throws FileNotFoundException,
IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
String encodedString = readFileAsString(encodedStringPath);
if(isPublicKeyAndDataBase64) {
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
Timber.w("Encoded String converted from base64: %s", decodeBase64ToBytesa(encodedString));
try {
PrivateKey priv = generatePrivateKey(factory, privateKeyPath);
Timber.i(String.format("Instantiated private key: %s", priv));
decipherString(priv, decodeBase64ToBytesa(encodedString));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return;
}
else
Timber.w("Encoded String: %s", encodedString);
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
PrivateKey priv = generatePrivateKey(factory, privateKeyPath);
Timber.i(String.format("Instantiated private key: %s", priv));
decipherString(priv, encodedString.getBytes());
PublicKey pub = generatePublicKey(factory, publicKeyPath);
Timber.i(String.format("Instantiated public key: %s", pub));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename, false);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
private static PublicKey generatePublicKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename, false);
byte[] content = pemFile.getPemObject().getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return factory.generatePublic(pubKeySpec);
}
private static void decipherString(PrivateKey privateKey, byte[] encodedStringData) {
byte[] dectyptedText = null;
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
dectyptedText = cipher.doFinal(encodedStringData);
Timber.w("Deciphered text is: %s", new String(dectyptedText));
}
catch (Exception e) {
e.printStackTrace();
}
}
static class PemFile {
private PemObject pemObject;
public PemFile(String filename, boolean isBase64) throws FileNotFoundException, IOException {
PemReader pemReader = null;
if(isBase64) {
Timber.i("reading base64 encoded pem file. base64DecodedString: %s", decodeBase64(filename));
pemReader = new PemReader(new StringReader(decodeBase64(filename)));
}
else
pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
}
catch (Exception e) {
e.printStackTrace();
}finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
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.