본문 바로가기
개발

AES256/ base64 암호화 with java

by 개발자종혁 2021. 4. 2.
728x90

build.gradle

dependencies {
...
    implementation 'org.springframework.boot:spring-boot-starter-security'

}

 

 

AES_Encryption.java


import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES_Encryption{

    static String key = "12345678901234567890123456789012";

    public static String encrypt(String plainText) throws Exception {
        SecretKey keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        //set iv as random 16byte 
        int ivSize = 16;
        byte[] iv = new byte[ivSize];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        AlgorithmParameterSpec ivspec = new IvParameterSpec(iv);

        // Encryption
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

        int blockSize = 128; //block size
        byte[] dataBytes = plainText.getBytes("UTF-8");

        //find fillChar & pad
        int plaintextLength = dataBytes.length;
        int fillChar = ((blockSize - (plaintextLength % blockSize)));
        plaintextLength += fillChar; //pad 

        byte[] plaintext = new byte[plaintextLength];
        Arrays.fill(plaintext, (byte) fillChar);
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        //encrypt
        byte[] cipherBytes = cipher.doFinal(plaintext);

        //add iv to front of cipherBytes
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
        outputStream.write( iv );
        outputStream.write( cipherBytes );

        //encode into base64
        byte [] encryptedIvText = outputStream.toByteArray();
        return new String(Base64.getEncoder().encode(encryptedIvText), "UTF-8");
    }

    public static String decrypt(String encryptedIvText) throws Exception {
        //decode with base64 decoder
        byte [] encryptedIvTextBytes = Base64.getDecoder().decode(encryptedIvText);

        // Extract IV.
        int ivSize = 16;
        byte[] iv = new byte[ivSize];
        System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);

        // Extract encrypted part.
        int encryptedSize = encryptedIvTextBytes.length - ivSize;
        byte[] encryptedBytes = new byte[encryptedSize];
        System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);



        // Decryption
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKey keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        AlgorithmParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] aesdecode = cipher.doFinal(encryptedBytes);

        // unpad
        byte[] origin = new byte[aesdecode.length - (aesdecode[aesdecode.length - 1])];
        System.arraycopy(aesdecode, 0, origin, 0, origin.length);

        return new String(origin, "UTF-8");
    }

}

App.java

public class App {
    public static void main(String[] args) throws Exception {

        AES_Encryption aes_Encryption = new AES_Encryption();
        String enc = aes_Encryption.encrypt("!시험용UTF-8글자");
        String enc2 = aes_Encryption.encrypt("!시험용UTF-8글자2Hello");
        String str = new String("!시험용UTF-8글자".getBytes("UTF-8"), "UTF-8");
        System.out.println(str);

        System.out.println(enc);
        System.out.println(enc2);

        String dec = aes_Encryption.decrypt(enc);
        String dec2 = aes_Encryption.decrypt(enc2);

        System.out.println(dec);
        System.out.println(dec2);

        String eg = "MTIzNDU2Nzg5MDEyMzQ1NpKG9iOsLurDQGjNctS8dRweDlSKz54lnFy4QgjtNTc1irYEkxNeoKYjNczhIeSD+RQu/+Btv3lJe6jZ/7MwAOlt8KnJLdlEyPaEaLMe0lFvcKkCopExbnTAnK4+a7Gvmy7EM/TcYSqlu7WBhQKwhfLA557w76BdEPCW0K7fVX81";
        String dec3 = aes_Encryption.decrypt(eg);
        System.out.println(dec3);

    }

}

python 암복호화 모듈

AES256/ base64 암호화 with python (tistory.com)

 

AES256/ base64 암호화 with python

1. install pycrytpodome pip install pycryptodome 2. python class import base64 from Crypto import Random from Crypto.Cipher import AES class AES256(): def __init__(self, key): self.bs = 128 self.key..

jonghyeok-dev.tistory.com

 

728x90

'개발' 카테고리의 다른 글

프로메테우스 관련 시작  (0) 2021.04.16
SPA(Single Page App)와 CSR(Client side rendering)  (0) 2021.04.06
DDD란?  (0) 2021.04.05
Springboot PasswordEncoder 등록  (0) 2021.04.05
SHA1 vs SHA2 차이점  (0) 2021.04.05

댓글