[Java] How to encrypt with AES encryption with standard library

Thing you want to do

--I want to encrypt and save token using Java standard library --When you get token information, you want to use it in a decrypted state. --I want to use AES encryption with the same key for encryption and decryption.

Sample encryption / decryption process

--The key used for encryption & decryption is 128bit (= 16byte / 16 alphanumeric characters) --If the cipher mode is CBC, an initial vector with the same length as the key is required.

Implementation example

CryptSample.java


package com.tamorieeeen.sample

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 *encryption/Decryption processing sample
 * @author tamorieeeen
 */
public class CryptSample {

  //algorithm/Block mode/Padding method
  private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
  //Key used for encryption & decryption
  private static final String ENCRYPT_KEY = "yourEncryptKey01";
  //Initialization vector
  private static final String INIT_VECTOR = "yourInitVector01";

  private final IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes());
  private final SecretKeySpec key = new SecretKeySpec(ENCRYPT_KEY.getBytes(), "AES");

  /**
   *Save token
   */
  public void saveToken(String token) {

    String encryptedToken = this.encryptToken(token);
    //Save encryptedToken in DB
    this.saveTokenToDb(encryptedToken);
  }

  /**
   *Encryption process
   */
  private String encryptToken(String token) throws Exception {

    Cipher encrypter = Cipher.getInstance(ALGORITHM);
    encrypter.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
    byte[] byteToken = encrypter.doFinal(token.getBytes());

    return new String(Base64.getEncoder().encode(byteToken));
  }

  /**
   *Get token
   */
  public String getToken() {

    //Get token from DB
    String encryptedToken = this.getEncryptedTokenFromDb();

    return this.decryptToken(encryptedToken);
  }

  /**
   *Decryption process
   */
  private String decryptToken(String encryptedToken) throws Exception {

    Cipher decrypter = Cipher.getInstance(ALGORITHM);
    decrypter.init(Cipher.DECRYPT_MODE, this.key, this.iv);
    byte[] byteToken = Base64.getDecoder().decode(encryptedToken);

    return new String(decrypter.doFinal(byteToken));
  }

  /**From here on down, create the methods you need**/

  /**
   *Save token in DB
   */
  private void saveTokenToDb(String encryptedToken) throws Exception {

    //Process to save encryptedToken in DB
  }

  /**
   *Get token from DB
   */
  private String getEncryptedTokenFromDb() throws Exception {

    //Process to get token from DB
  }
}

reference

[Java] Use cryptography with standard library Let's do cryptographic processing!

Recommended Posts

[Java] How to encrypt with AES encryption with standard library
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
How to encrypt and decrypt with RSA public key in Java
[Java] How to test for null with JUnit
[Java] How to get and output standard input
How to use Java framework with AWS Lambda! ??
How to use Java API with lambda expression
Encrypt / decrypt with AES256 in PHP and Java
How to call functions in bulk with Java reflection
[Java] How to omit spring constructor injection with Lombok
How to deploy Java to AWS Lambda with Serverless Framework
How to use java non-standard library on IntelliJ IDEA
How to use Z3 library in Scala with Eclipse
How to output standard from an array with forEach
How to use Truth (assertion library for Java / Android)
How to use JDD library in Scala with Eclipse
How to build Java development environment with VS Code
[Java] How to start a new line with StringBuilder
Code to use when you want to process Json with only standard library in Java
How to lower java version
[Java] How to use Map
Java to play with Function
Java --How to make JTable
How to use java Optional
How to minimize Java images
How to write java comments
RSA encryption / decryption with java 8
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to number (number) with html.erb
How to use Java Map
How to update with activerecord-import
How to set Java constants
Connect to DB with Java
Connect to MySQL 8 with Java
How to use Java variables
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array
How to decompile apk file to java source code with MAC
How to handle exceptions coolly with Java 8 Stream or Optional
Investigated how to call services with Watson SDK for Java
[Java] I want to test standard input & standard output with JUnit
How to scroll horizontally with ScrollView
Create a simple web server with the Java standard library com.sun.net.httpserver
How to get started with slim
Studying Java # 6 (How to write blocks)
Use Microsoft Graph with standard Java
[Java] Points to note with Arrays.asList ()
[Java] How to update Java on Windows
How to make a Java container
How to disassemble Java class files
How to enclose any character with "~"
How to use Java HttpClient (Post)
[Java] How to use join method
Dare to challenge Kaggle with Java (1)