我正在尝试在java中加密/解密文件,并且文件将在另一侧的node.js中解密/加密。
我使用以下命令生成密钥库文件
keytool -genseckey -keystore -storetype jceks -storepass -keyalg AES -keysize 256 -alias -keypass
然后我以base64格式编码密钥并发送给其他方。
在我的java代码中,我不使用base64形式的密钥。我只是从密钥库加载密钥,初始化我的密码并加密文件。
然后我将加密文件发送给其他方。然而他们无法解密它。同样,如果他们加密它并尝试解密它,我得到BadPaddingException。到底是怎么回事。是因为他们使用base64编码的密钥,我不是吗?其余的所有事情在算法,操作方式上都是一样的。
这是我正在使用的解密功能:
public void decryptFile(InputStream inputStream, OutputStream outputStream)
throws Exception {
try {
long totalread = 0L;
int nread = 0;
byte[] inbuf = new byte[128];
mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mInitVec = new byte[16];
inputStream.read(mInitVec);
mDecipher.init(2, loadKey(), new IvParameterSpec(mInitVec));
CipherInputStream cin = new CipherInputStream(inputStream, mDecipher);
while ((nread = cin.read(inbuf)) > 0) {
totalread += nread;
byte[] trimbuf = new byte[nread];
for (int i = 0; i < nread; i++) {
trimbuf[i] = inbuf[i];
}
outputStream.write(trimbuf);
}
outputStream.flush();
} catch (Exception ex) {
Logger.getLogger(FileEncryptor.class.getName()).log(Level.SEVERE, null, ex);
throw ex;
}
}
And here is the loadKey()
try
{
KeyStore keystore = KeyStore.getInstance("JCEKS");
FileInputStream keystoreStream = new FileInputStream(keyFile);
keystore.load(keystoreStream, storePassword.toCharArray());
if (!keystore.containsAlias(keyAlias)) {
throw new RuntimeException("Alias for key not found");
}
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyPassword.toCharArray());
KeyStore.SecretKeyEntry skEntry = (KeyStore.SecretKeyEntry)keystore.getEntry(keyAlias, protParam);
SecretKey mySecretKey = skEntry.getSecretKey();
byte[] enc = new byte['Ā'];
enc = mySecretKey.getEncoded();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error reading key from keystore. Please check if the keystore '" + keyFile + "' exists and is valid."); }
SecretKey mySecretKey;
FileInputStream keystoreStream; KeyStore keystore; return mySecretKey;
}
另一方正在使用node.js,代码是
//String to encrypt
var plaintext = data.Body;
//initialisation vector
var iv = crypto.randomBytes(16);
//cipher based on provided key and iv
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
//encrypt the plaintext using aes-256-cbc
var encrypted = cipher.update(plaintext);
var finalBuffer = Buffer.concat([encrypted, cipher.final()]);
//Need to retain IV for decryption, so this can be prepended to the output
var encryptedbuffer = Buffer.concat([iv, finalBuffer]);
var encryptedstring = iv.toString() + finalBuffer.toString();