Как зашифровать и расшифровать переменную типа String
Нужно зашифровать данные переменной а потом расшифровать ( какие-то ключи как это сделать я не понимаю). Саму механику. Можно любыми доступными способами .
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
Можно например использовать Cipher таким образом:
public static SecretKey generateKey()
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return secret = new SecretKeySpec(password.getBytes(), "AES");
}
public static byte[] encryptMsg(String message, SecretKey secret)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
return cipherText;
}
public static String decryptMsg(byte[] cipherText, SecretKey secret)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
{
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
return decryptString;
}
чтобы зашифровать делаем так:
SecretKey secret = generateKey();
EncUtil.encryptMsg(String toEncrypt, secret))
чтобы расшифровать делаем так:
EncUtil.decryptMsg(byte[] toDecrypt, secret))
Вот есть туториал по данному вопросу. Документация и статьи: 1 и 2.