【发布时间】:2014-03-07 01:07:33
【问题描述】:
我正在为一个客户做这个项目,我目前坚持的部分涉及获取一个 XML 字符串并对其进行加密 - 这不需要是最先进的,它只需要对其进行加密和解密它使用密码。
到目前为止,用户输入了我使用 SHA-256 进行哈希处理的密码,然后我尝试这样做并对其进行加密:
public static String encryptString(String password, String source, String fileName, String fileDir) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, FileNotFoundException, IOException {
FileOutputStream fos = null;
CipherInputStream cis;
byte key[] = password.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(key, "DES");
Cipher encrypt = Cipher.getInstance("DES/ECB/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey);
InputStream fileInputStream = new ByteArrayInputStream(source.getBytes());//Here I am getting file data as byte array. You can convert your file data to InputStream by other way too.
File dataFile = new File(fileDir, fileName); //dataDir is location where my file is stored
if (!dataFile.exists()) {
cis = new CipherInputStream(fileInputStream, encrypt);
try {
fos = new FileOutputStream(dataFile);
byte[] b = new byte[32];
int i;
while ((i = cis.read(b)) != -1) {
fos.write(b, 0, i);
}
return fileName;
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
cis.close();
fileInputStream.close();
} catch (IOException e) {
//IOException
}
}
}
return "";
}
传入的密码是散列密码 - 从这里我尝试运行它,但我得到:
java.security.InvalidKeyException:无效密钥长度:64 字节异常。
有人可以帮忙吗?
或者告诉我用密码加密 XML 文件的更好方法?
谢谢
【问题讨论】:
标签: java xml encryption sha256 des