I m trying to use an AES cipher to encrypt some bytes but it s returning a silent error, meaning I enter something like:
byte[] raw = new String("Test","UTF8").getBytes("UTF8");
它赢得了任何回报。 我认为,问题是<代码>。 ByteArrayInput/OutputStreams
,但我不知道如何以任何其他方式做到这一点。
这里是有关的法典。
public byte[] encrypt(byte[] in) {
byte[] encrypted = null;
try {
aesCipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
ByteArrayInputStream bais = new ByteArrayInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream(bais.available());
CipherOutputStream os = new CipherOutputStream(baos, aesCipher);
copy(bais, os);
os.flush();
byte[] raw = baos.toByteArray();
os.close();
encrypted = Base64.encodeBase64(raw);
} catch (FileNotFoundException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
}
return encrypted;
}
这里的另一职能是:
public void encrypt(File in, File out) {
try {
aesCipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
FileInputStream is;
is = new FileInputStream(in);
CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), aesCipher);
copy(is, os);
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(FileEncryption.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void copy(InputStream is, OutputStream os) throws IOException {
int i;
byte[] b = new byte[2048];
while ((i = is.read(b)) != -1) {
os.write(b, 0, i);
}
}