Problems with encryption/decryption
I have a problem: i need to encrypt/decrypt file, generally it works, but sometimes (randomly) it decrypt's some lines or some characters wrongly (uncnown format) Example:
Type=Device
Name=sveta
IpAd胖qr
Pa詓word=xxxx
User=user1
instead of
Type=Device
Name=sveta
IpAddr=1.1.1.1
Password=xxxx
User=user1
CODE:
private static final String MD5_DES = "PBEWithMD5AndDES";
private static final byte[] SALT = {(byte) 0xd3, (byte) 0xc3, (byte) 0xff, (byte) 0x8e,(byte) 0x56, (byte) 0xf7, (byte) 0xd6, (byte) 0x82};
private void init() {
try {
paramSpec = new PBEParameterSpec(salt, 20);
SecretKeyFactory kf = SecretKeyFactory.getInstance(MD5_DES);
passwordKey = kf.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 20));
c = Cipher.getInstance(MD5_DES);
}
catch(Exception e) {
throw new SecurityException("Some problems while JceUtility initialization: " + e.getMessage());
}
}
private String readEncryptedFile(File file) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(file.exists() && file.canRead()) {
DataInputStream in = null;
DataOutputStream out = null;
//read and decrypt file content
try {
out = new DataOutputStream(baos);
in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
byte[] b = null;
int n = -1;
while((n = in.available()) > 0){
b = new byte[n];
in.read(b);
decrypt(new DataInputStream(new ByteArrayInputStream(b)),out);
}
}
catch(Exception e) {
throw new IOException("Reading encrypted file: " + e.getMessage());
}
finally{
try {
in.close();
out.close();
}
catch(Throwable e) { // ignore
}
}
}
else
{
throw new IOException("Error while initializing file '" + file.getAbsolutePath() + "'. It is not readable.");
}
return baos.toString();
}
public void decrypt(DataInputStream in, DataOutputStream out)
throws IOException, InvalidKeyException, InvalidAlgorithmParameterException {
c.init(Cipher.DECRYPT_MODE, passwordKey, paramSpec);
CipherInputStream cis = new CipherInputStream(in, c);
int i = -1;
String s = EMPTY;
while ((i = cis.read()) >= 0) {
s += (char) i;
out.write(i);
}
}public void encrypt(DataInputStream in, DataOutputStream out)
throws IOException, InvalidKeyException, InvalidAlgorithmParameterException {
c.init(Cipher.ENCRYPT_MODE, passwordKey, paramSpec);
CipherInputStream cis = new CipherInputStream(in, c);
int i = -1;
while ((i = cis.read()) >= 0) {
out.write(i);
}
}
public String encrypt(String s)
throws IOException, InvalidKeyException, InvalidAlgorithmParameterException {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(s.getBytes()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
encrypt(in, out);
out.close();
in.close();
return baos.toString();
}
What will be a problem?

