Criptografia Assimétrica Java Usando JDK

Casos de uso

  • Criptografia assimétrica

Versão Java

  • JDK 11

Código de exemplo para criptografia assimétrica RSA 4096 usando Java

package com.cryptoexamples.java;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Exemplo para criptografia assimétrica e descriptografia de uma string em um método.
 * - Geração de par de chaves público e privado RSA 4096 bits
 * - Codificação BASE64 como representação para as matrizes de bytes
 * - Codificação UTF-8 de Strings
 * - Exception handling
 */
public class ExampleAsymmetricStringEncryption {
  private static final Logger LOGGER = Logger.getLogger(ExampleAsymmetricStringEncryption.class.getName());

  public static void main(String[] args) {
    String plainText = "Text that is going to be sent over an insecure channel and must be encrypted at all costs!";
    try {
      // GENERATE NEW KEYPAIR
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      /* @see https://www.keylength.com/ */
      keyPairGenerator.initialize(4096);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      // ENCRYPTION
      Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
      cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

      byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

      // CONVERSION of raw bytes to BASE64 representation
      String cipherText = Base64.getEncoder().encodeToString(cipherTextBytes);

      // DECRYPTION
      cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
      byte[] decryptedCipherTextBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
      String decryptedCipherText = new String(decryptedCipherTextBytes,StandardCharsets.UTF_8);

      LOGGER.log(Level.INFO, () -> String.format("Decrypted and original plain text are the same: %b", decryptedCipherText.compareTo(plainText) == 0));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterException  e) {
      LOGGER.log(Level.SEVERE, e.getLocalizedMessage());
    }
  }
}

Referencia

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.