KeyStore loading causing EOFException error on Android - java

I have some code for my app that creates a keystore in android,
creates some default keys then saves the keystore.
Later on the code tries to reload the keystore, on the emulator this
runs fine however when run on a phone I get an EOFException. Any
advice on where I'm going wrong?
An out take of the code is below:
In the class I have the following variables
static KeyStore keyStore;
String filenameKeyStore = "KeyStore.kstore";
Then the following two functions
public KeyHandler(Context context) {
if(keyStore == null) {
Log.d("KeyStore", "Keystore is null so loading");
if(initialiseKeyStore(context) == false) {
// KeyStore failed to initialise
Log.e("ERROR", "Store failed to initialise");
}
}
}
private boolean initialiseKeyStore(Context context) {
FileInputStream input = null;
try {
// Get an instance of KeyStore
keyStore = KeyStore.getInstance("BKS");
// Load the KeyStore file
try {
// Try and open the private key store
input = context.openFileInput(filenameKeyStore);
} catch (FileNotFoundException e) {
// If the file doesn't exist then create the file, a ECDH key and
store the key
Log.w("Warning","File does not exist, creating new file");
try {
// Load the default Key Store
keyStore.load(null, null);
// Create the file
FileOutputStream output =
context.openFileOutput(filenameKeyStore, 0);
// Reset private key
resetPrivateKey(context);
// Save the key
keyStore.store(output, "password".toCharArray());
// Close the keystore and set the input stream
output.close();
input = context.openFileInput(filenameKeyStore);
// Reset the keyStore
keyStore = KeyStore.getInstance("BKS");
} catch (FileNotFoundException ee) {
Log.e("ERROR", "File not found, even though we just created it");
return false;
} catch (NoSuchProviderException e1) {
// BC isn't working exit
e1.printStackTrace();
System.exit(1);
} catch (InvalidAlgorithmParameterException e1) {
Log.e("ERROR", "The algorithm used for secure algorithm is
incorrect");
e1.printStackTrace();
return false;
}
}
// Load the store
keyStore.load(input, "password".toCharArray());
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (EOFException e) {
// Where the exception is caught
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (NoSuchProviderException e) {
// Serious error, return
e.printStackTrace();
System.exit(1);
}
return true;
}

This usually happens when the keystore file is corrupted. We just had (again) such issue with a keystore sent by an external dev who was unable to recall how exactly did he created the keystore file.
Create a new keystore file and import the certificate(s) - this will solve the problem.

Related

how to confirm a file is a picture file with java language?

I want to know how can I use java to confirm a file is a picture file.
I have tried the following code:
public static void main(String[] args) {
// get image format in a file
File file = new File("C:/Users/dell、/Desktop/4.xlsx");
// create an image input stream from the specified fileDD
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
System.out.println("Not a picture file");
throw new RuntimeException("No readers found! Unable to read the uploaded file");
}
// get the first reader
ImageReader reader = iter.next();
try {
System.out.println("Format: " + reader.getFormatName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close stream
if (iis != null){
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But it doesn't work perfectly! It shows an exception once the file is not a picture file, so I want to find a better way.
There are too many image extensions. Maybe the best way to validate if a file is an image, is using Regular Expressions. Something like this...
([^\s]+(\.(?i)(jpg|png|gif|bmp|MORE|IMAGE|EXTENSIONS))$)
Here is a complete example of the implementation.
Use ImageIO#read.
public static boolean isPictureFile(File file){
try{
return ImageIO.read(file) != null;
}catch(Exception ex){
return false;
}
}
Basically, the method ImageIO.read(File) will return a BufferedImage object when it successfully read the image file, a null otherwise. All we have to do is to let ImageIO read the file and check if it returns a null or not, and if there it throws an exception for whatever reason, we can safely assume the file is not a picture file.

read a doc and rewrite with Apache POI ,but fail to open with office

I'm trying to modify a doc with Apache POI in Java.
At first the test.doc cannot be read with a exception raised up :
"org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x6576206C6D783F3C, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
"
So I saved the doc as "word 97 - 03" format,and then POI can read the doc properly.
But when I try to rewrite the content to a new file with nothing changed, the file output.doc cannot be opened by MS Office.
When I make a new doc myself with MS Office, the POI works well, everything goes right.
So the problem is "test.doc".
The test.doc is generated by some sort of a program which I can't access the code,so I don't know what goes wrong.
My question is :
1.As test.doc can be read by MS Office why can't POI without saving as a new format doc?
2.As the POI can read the doc, why it cannot write back to a new file(MS Office can't open)?
Here is my code:
FileInputStream fis = null;
try {
fis = new FileInputStream("test.doc");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POIFSFileSystem pfs = null;
try {
pfs = new POIFSFileSystem(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HWPFDocument hwdf = null;
try {
hwdf = new HWPFDocument(pfs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("output.doc"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hwdf.write(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
pfs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The HEX stuff read as ASCII and read little-endian converts to <?xml ve, which indicates that test.doc is some other format than actually .doc/.docx.
Word will open other data-formats gracefully sometimes, upon saving it will be saved correctly in the Word-Format.
Therefore you will need to use a hex-editor to take a look at the contents of test.doc and if it is really in some broken format you need to find out where it is coming from and how the creation of that file can be fixed.

RSA Enabled Simple Java Chat - Not PKCS#1 block type 2 or Zero padding

I created a simple java chat application . Below is the follow
Run ChatClient.java - Dialog box is shown where user enters username. Then private key and public key are generated and stored in C:/username/publickey,C:/username/privatekey.
Above step repeats when we run ChatClient.java again.
Then user1 sends message to User2 in encrypted form using User2 public key (Which is working fine)(after encryption , message is stored in text file) then User2 clicks decrypt button which decrypts the text (reads the encrypted text from file) using User 2 private key then display in textarea.
When I trying to decrypt I am getting "Not PKCS#1 block type 2 or Zero padding" exception
public static byte[] encrypt(String text, PublicKey key) throws {
// 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);
byte[] cipherText = cipher.doFinal(text.getBytes("UTF8"));
return org.apache.commons.codec.binary.Base64.encodeBase64(cipherText);
}
public static String decrypt(String text, PrivateKey key) throws {
byte[] dectyptedText = null;
// 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);
byte[] byteCipherText =org.apache.commons.codec.binary.Base64.decodeBase64(text):
byte[] cipherData = cipher.doFinal(byteCipherText);
return new String(dectyptedText);
}
private void btnDecryptActionPerformed(ActionEvent evt) throws {
String name11 = this.getTitle();
String test90 = null;
String PRIVATE_KEY_FILE = "C:/keys/"+name11+"/private.key";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("cipher.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while(in.ready())
{
String stest= in.readLine();
test90 = stest;
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PrivateKey privateKey = null;
try {
privateKey = (PrivateKey) inputStream.readObject();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PrivateKey privatekey = (PrivateKey) inputStream.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String plainText;
// byte[] test100 = test90.getBytes();
// out.println(test100);
plainText = decrypt(test90, privateKey); (Getting Error Here)
decryptText.append(plainText);
}
The highlighted code below means test90 only contains the last line in the cipher.txt file. Does cipher.txt contain 1 line only? If you want to read in everything, you need to concatenate each line as you read it in.
while(in.ready())
{
String stest= in.readLine();
test90 = stest;
}
It is also a good idea to System.out the variable test90 in the decrypt method to be sure that you're getting the expected base64 data to be decrypted.

Self-signed certificate

I use a hosting with a self-signed certificate. So I downloaded the certificate from my domain https://www.marpel.cz/ and created .bks file using http://portecle.sourceforge.net/.
I need to establish the https connection and retrieve data from my webservice. I use ksoap2 library. I have copied and used a class ConnectionWithSelfSignedCertificate stated in ksoap2 wiki.
This is the way I create a keyStore
MainActivity.java
// Get an instance of the Bouncy Castle KeyStore format
try {
this.keyStore = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = this.getApplicationContext().getResources().openRawResource(R.raw.myCer);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
this.keyStore.load(in, "myPass".toCharArray());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
this.sslSocketFactory = new ConnectionWithSelfSignedCertificate(this.keyStore).getSSLSocketFactory();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And this is a code from AsyncTask
background task
final HttpsTransportSE transportSE = new HttpsTransportSE(URL, PORT, SERVICE, TIMEOUT);
try {
((HttpsServiceConnectionSE) transportSE.getServiceConnection()).setSSLSocketFactory(this.sslSocketFactory);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
If I call transportSE.call(SOAP_ACTION, envelope); I get IOException, Hostname 'www.marpel.cz' was not verified. What do I do wrong?
I have an ICS 4.1.2 device.
Firstly, do you use self signed certificate?
If yes, then follow this link: android-webservices-via-ksoap2-https
You need extra classes for creating https connection and accepting of the certificate. When everything is prepared, you can call your transportSE.
The code in my first post works fine. I have found out that the self-signed certificate was issued for different domain. I fixed the certificate and everything works fine.
The fixed certificate runs here https://www.marpel.cz:445/
Thank you, Martin.

Extracting a file with JUnrar

I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}

Categories

Resources