Вопрос

I'm new to cryptography but I'm planning on using it in some later applications.

I would like to know if there is some component I am missing in this short demo program I've made.

I know I'm making an assumption with the 300 bytes, if there is a way to get around guessing array size I would like to know,

import java.io.*;
import java.security.GeneralSecurityException;
import java.security.spec.KeySpec;
import java.util.Arrays;


import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;

public class CipherStreamDemo {
private static final byte[] salt={
    (byte)0xC9, (byte)0xEF, (byte)0x7D, (byte)0xFA,
    (byte)0xBA, (byte)0xDD, (byte)0x24, (byte)0xA9
};
private Cipher cipher;
private final SecretKey key;
public CipherStreamDemo() throws GeneralSecurityException, IOException{
    SecretKeyFactory kf=SecretKeyFactory.getInstance("DES");
    KeySpec spec=new DESKeySpec(salt);
    key=kf.generateSecret(spec);
    cipher=Cipher.getInstance("DES");
}
public void encrypt(byte[] buf) throws IOException, GeneralSecurityException{
    cipher.init(Cipher.ENCRYPT_MODE,key);
    OutputStream out=new CipherOutputStream(new FileOutputStream("crypt.dat"), cipher);
    out.write(buf);
    out.close();
}
public byte[] decrypt() throws IOException, GeneralSecurityException{
    cipher.init(Cipher.DECRYPT_MODE, key);
    InputStream in=new CipherInputStream(new FileInputStream("crypt.dat"), cipher);
    byte[] buf=new byte[300];
    int bytes=in.read(buf);
    buf=Arrays.copyOf(buf, bytes);
    in.close();
    return buf;
}
public static void main(String[] args) {
    try{
        CipherStreamDemo csd=new CipherStreamDemo();
        String pass="thisisasecretpassword";
        csd.encrypt(pass.getBytes());
        System.out.println(new String(csd.decrypt()));
        }catch(Exception e){
            e.printStackTrace();
        }
}
}
//Output: thisisasecretpass
Это было полезно?

Решение

You're assuming that the input is going to be exactly 300 bytes, and you're also assuming you've read it all, in a single read. You need to keep reading until read() returns -1.

I don't see any point in the object streams. They're only adding overhead. Remove them.

Другие советы

This

int bytes=in.read(buf);

is almost always wrong and should be done like

for(int total = bytes.length; total > 0;)
{
    final int read = in.read(buf, buf.length - total, total);

    if (read < 0)
    {
        throw new EOFException("Unexpected end of input.");
    }

    total -= read;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top