AESGCMNoPadding加密(java)AES/GCM/NoPadding 加密(java)
之前使⽤AES加密,sonar扫描规定使⽤AES/GCM/NoPadding⽅式加密,踩了⼀些坑,以下是代码。key值:
public static final String AES_KEY = "sOWGI8LvFnvyH19rs2DytdIIrUOL6ott";
public  final static int GCM_IV_LENGTH = 12;
public  final static int GCM_TAG_LENGTH = 16;
加密:
public static String encrypt(String privateString, String key)  {
key = garbleSalt(key);
try {
byte[] raw = Bytes();
byte[] iv = new byte[GCM_IV_LENGTH];
(new SecureRandom()).nextBytes(iv);
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Instance("AES/GCM/NoPadding");
GCMParameterSpec ivSpec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, iv);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] ciphertext = cipher.Bytes("UTF8"));
byte[] encrypted = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, encrypted, 0, iv.length);
System.arraycopy(ciphertext, 0, encrypted, iv.length, ciphertext.length);
String encoded = Encoder().encodeToString(encrypted);
return encoded;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
获得256位keyjava加密方式有哪些
private static String  garbleSalt(String src) {
if (StringUtils.isEmpty(src)) {
return AES_KEY;
} else {
src += AES_KEY;
System.out.println(src);
return src.substring(0, 32);
}
}
解密:
public static String decrypt(String encrypted,String key) {
key = garbleSalt(key);
System.out.println("key=" + key + "keylength=" + key.length() );
try {
byte[] raw = Bytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
byte[] decoded = MimeDecoder().decode(encrypted);
byte[] iv = pyOfRange(decoded, 0, GCM_IV_LENGTH);
Cipher cipher = Instance("AES/GCM/NoPadding");
GCMParameterSpec ivSpec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
System.out.println("decoded.length" + decoded.length);
System.out.println("GCM_IV_LENGTH" + (decoded.length - GCM_IV_LENGTH));
System.out.println("decoded" + decoded);
byte[] ciphertext = cipher.doFinal(decoded, GCM_IV_LENGTH, decoded.length - GCM_IV_LENGTH);            String result = new String(ciphertext, "UTF8");
return result;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。