--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.
--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.
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
}
}
[Java] Use cryptography with standard library Let's do cryptographic processing!
Recommended Posts