前言:前面已经写了nifi数据库解密,我们也可以使用nifi这种加密方法去进行加密,方便以后使用.nifi数据库连接密码解密
加密:
package com.company;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
public class EncryptionTest2 {
private static final String DEFAULT_FLOW_ALGORITHM = "PBEWITHMD5AND256BITAES-CBC-OPENSSL";
private static final String DEFAULT_PROVIDER = BouncyCastleProvider.PROVIDER_NAME;
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, BadPaddingException, IOException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeySpecException, InvalidKeyException {
//随机生成16位的盐
byte[] encryptionSalt = new byte[16];
new SecureRandom().nextBytes(encryptionSalt);
//nififtw!为nifi定义的口令,可以自己修改
Cipher cipher= getCipher("nififtw!",encryptionSalt);
//test为需要加密的密码
String pass = encryptFlowElement("test",encryptionSalt,cipher);
System.out.println(pass);
}
private static String encryptFlowElement(String plaintext, byte[] saltBytes, Cipher encryptCipher) throws BadPaddingException, IllegalBlockSizeException, IOException {
byte[] plainBytes = plaintext.getBytes(StandardCharsets.UTF_8);
byte[] cipherBytes = encryptCipher.doFinal(plainBytes);
byte[] saltAndCipherBytes = conByteArray(saltBytes, cipherBytes);
String hexEncodedCipherText = Hex.encodeHexString(saltAndCipherBytes);
return "enc{"+hexEncodedCipherText+"}";
}
public static byte [] conByteArray(byte [] arr1,byte [] arr2) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(arr1);
outputStream.write(arr2);
return outputStream.toByteArray();
}
//这个password 是口令
private static Cipher getCipher(String password,byte [] saltBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {
Cipher encryptCipher = Cipher.getInstance(DEFAULT_FLOW_ALGORITHM, DEFAULT_PROVIDER);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DEFAULT_FLOW_ALGORITHM, DEFAULT_PROVIDER);
SecretKey pbeKey = keyFactory.generateSecret(keySpec);
PBEParameterSpec parameterSpec = new PBEParameterSpec(saltBytes,1000);
encryptCipher.init(Cipher.ENCRYPT_MODE, pbeKey, parameterSpec);
return encryptCipher;
}
}
有兴趣的同学可以看我的微信公众号,后面会陆续开发