我正在写一个Vigenere密码。它适用于普通的char,但是当我在Mac键盘上使用额外的char(例如使用选项和c)时,它会中断。是因为它超出了char范围吗?
Output using read byte individually
hello testing long output!@#)!(!*!(@()asdfasdfljkasdfjË©âå¬ÃËââÃ¥ËÃâçËâËøÅËèâÏåøÃ
Output using read(byte[])
hello testing long output!@#)!(!*!(@()asdfasdfljkasdfjᅨルᅡᄅ¬ネニᅢᆬᅡᆲᅢ゚ᅨレ¬ネツ¬ネニᅢᆬᅨルᅢ゚¬ネニᅢ뎨ニ¬ネムᅨニᅢ쟤モᅨニᅢ゚ᅡᄄ¬ネツᅬタᅢᆬᅢ재゚
代码:
import java.io.*;
class VigenereFilterInputStream extends FilterInputStream {
private final byte[] key;
private int index = 0;
VigenereFilterInputStream(InputStream in, byte[] k) {
super(in);
key = k.clone();
}
public int read() throws IOException {
int c = super.read();
if (c == -1)
return -1;
int out = c ^ key[index];
index ++;
index %= key.length;
return out;
}
public int read(byte[] b) throws IOException {
int result = in.read(b);
for(int i = 0; i < b.length; i++) {
b[i] = (byte) (b[i] ^ key[i % key.length]);
}
return result;
}
}
class VigenereFilterOutputStream extends FilterOutputStream {
private final byte[] key;
VigenereFilterOutputStream(OutputStream out, byte[] k) {
super(out);
key = k.clone();
}
public void write(byte[] b) throws IOException {
byte[] out = new byte[b.length];
for(int i = 0; i < b.length; i++) {
out[i] = (byte) (b[i] ^ key[i % key.length]);
}
super.write(out);
}
}
class Vigenere {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
throw new Exception("Missing filename");
}
File f = new File(args[0]);
byte[] text = "hello testing long output!@#)!(!*!(@()asdfasdfljkasdfj˙©∆å¬ß˚∂∆å˙ß∆çˆ∑ˆøœˆß¨∂πåøß".getBytes();
byte[] key = "hello".getBytes();
FileOutputStream os = new FileOutputStream(f);
VigenereFilterOutputStream encrypt = new VigenereFilterOutputStream(os, key);
encrypt.write(text);
FileInputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
VigenereFilterInputStream decrypt = new VigenereFilterInputStream(bis, key);
bis.mark(text.length);
int c;
while((c = decrypt.read()) != -1) {
System.out.print((char) c);
}
System.out.println();
bis.reset();
byte[] b = new byte[text.length];
decrypt.read(b);
for(byte d: b) {
System.out.print((char) d);
}
System.out.println();
}
}