对于我的3DES加密算法,将FileInputStream和FileOutputStream转换为CipherInputStream和CipherOutputStream时遇到一些问题。有人可以指导我正确的方法吗?我最终收到错误:“ CipherInputStream无法解析为类型”。抱歉,这很明显。
t.prototype.downloadXlsx = function () {
var t = this, e = {
date_from: this.helpers.formatDate(this.filter.date_from),
date_to: this.helpers.formatDate(this.filter.date_to),
download: "fees"
};
this.http.get("team-accounts/" + this.route.snapshot.params.id, e).subscribe(function (n) {
var i = {type: 'application/octet-stream'},
r = t.account.team.name + "_summary_" + e.date_from + "_" + e.date_to + ".xlsx";
t.helpers.downloadXlsxFile(n._body, i, r);
})
t.prototype.downloadXlsxFile = function (t, e, n, i) {
var r = new Blob(t], e);
if (navigator.msSaveBlob) navigator.msSaveBlob(r, n); else {
var a = document.createElement("a");
if (void 0 !== a.download) {
var o = i || document.body, s = URL.createObjectURL(r);
a.setAttribute("href", s), a.setAttribute("download", n), a.style.visibility = "hidden", o.appendChild(a), a.click(), o.removeChild(a)
}
}
答案 0 :(得分:1)
这对我有用:
public class Cypher {
// password to encrypt the file
private static final String passKey = "tkfhkggovubm";
public static void main(String[] args) throws Exception {
try (FileInputStream inputFile = new FileInputStream("plainfile.txt");
FileOutputStream outputFile = new FileOutputStream("plainfile.des");) {
byte[] salt = new byte[8];
SecureRandom r = new SecureRandom();
r.nextBytes(salt);
outputFile.write(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(passKey.toCharArray());
SecretKeyFactory secretKeyFactory = SecretKeyFactory
.getInstance("PBEWithSHA1AndDESede");
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 99999);
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
try (CipherOutputStream cis = new CipherOutputStream(outputFile, cipher);) {
IOUtils.copy(inputFile, cis);
}
}
try (FileInputStream fis = new FileInputStream("plainfile.des");
FileOutputStream outputFile = new FileOutputStream("plainfile.txt2");) {
byte[] salt = new byte[8];
int saltBytes = fis.read(salt);
if (saltBytes!=salt.length)
throw new Exception("Huh???");
PBEKeySpec pbeKeySpec = new PBEKeySpec(passKey.toCharArray());
SecretKeyFactory secretKeyFactory = SecretKeyFactory
.getInstance("PBEWithSHA1AndDESede");
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 99999);
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
try (CipherInputStream cis = new CipherInputStream(fis, cipher);) {
IOUtils.copy(cis, outputFile);
}
}
}
}
执行完主体后,plainfile.txt
和plainfile.txt2
相等。 plainfile.des
被加密。
IOUtils.copy
是apache.commons-io中的一种方法,该方法在内部保留缓冲区,并将所有字节从一个流写入另一个流。
只是将byte[] input = ...
提取到方法中,再加上使用try-with-resources。
这样可以使代码简单易读。