我是密码学的新手,但我打算在以后的某些应用程序中使用它。
我想知道我在这个简短的演示程序中是否缺少某些组件。
我知道我正在做300字节的假设,如果有办法绕过猜测数组大小我想知道,
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
答案 0 :(得分:2)
你假设输入正好是300字节,你也假设你已经读过一次,只需一次读取。你需要继续阅读,直到read()返回-1。
我没有在对象流中看到任何意义。他们只是增加了开销。删除它们。
答案 1 :(得分:0)
此
int bytes=in.read(buf);
几乎总是错误的,应该像
一样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;
}