Escolha uma Página

Como encriptar uma String no Spring

Escrito por Alisson

outubro 30, 2023

Acredito que todos os programadores ou passaram ou vão passar por essa situação, em que temos um campo em um objeto que precisamos salvar ele em um banco de dados de forma encriptada.

Nesse post vou mostrar como fazer para encriptar esse campo antes de salvar ele na nossa base de dados.

Para podermos encriptar o nosso campo, vamos precisar de um parâmetro de spec e uma secret. Abaixo vou mostrar como gerar esses valores.

public static IvParameterSpec generateIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    return new IvParameterSpec(iv);
  }

Para gerar a secret podemos gerar de duas formas, aleatória ou usando as nossas chaves.

1 – Aletória

public static SecretKey generateKey(int n) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(n);
    SecretKey key = keyGenerator.generateKey();
    return key;
  }

2 – Utilizando nossas chaves

public static SecretKey generateKey(String password, String salt) throws NoSuchAlgorithmException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
    SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    return key;
  }

Agora que temos os dados necessários vamos ver como encriptar e descriptar a nossa string.

 public static String encrypt(String algorithm, String input, SecretKey key,
      IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
      InvalidAlgorithmParameterException, InvalidKeyException,
      BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    final var cipherText =  cipher.doFinal(input.getBytes());

    return Base64.getEncoder()
        .encodeToString(cipherText);
  }
  public static String decrypt(String algorithm, String cipherText, SecretKey key,
      IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
      InvalidAlgorithmParameterException, InvalidKeyException,
      BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key, iv);
    byte[] plainText = cipher.doFinal(Base64.getDecoder()
        .decode(cipherText));
    return new String(plainText);
  }

Com esses métodos criados podemos utilizar da seguinte forma.

public static void testSecurity() {

    final var ivParameter = generateIv();
    final var key = generateKey("password", "salt");
    
    final var encrypted = encrypt("AES/CBC/PKCS5Padding", "string to encrypt", key, ivParameter);
    final var decrypted = decrypt("AES/CBC/PKCS5Padding", encrypted, key, ivParameter);
    
    if (decrypted.equals("string to encrypt")) {
      System.out.println("Success encrypt");
    } else {
      System.out.println("Fail encrypt");
    }
  }

Você pode gostar…

Parse local date to UTC

Parse local date to UTC

Precisa converter Local date para UTC. private static final DateTimeFormatter FORMATTER_ZONED =...

0 comentários

Enviar um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *