package com.interplug.qcast.config.jasypt;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 *
 * <pre>
 * 설정파일(yml or properties)에 있는 password 를 암호화
 * </pre>
 *
 * @author KimYoungHyun (youngh.kim@kt.com)
 */
@Configuration
public class JasyptConfig {

  private static final String KEY = "qcast_jasypt_key";
  private static final String ALGORITHM = "PBEWithMD5AndDES";

  /**
   *
   *
   * <pre>
   * jasyptEncryptor 설정
   * </pre>
   *
   * @author KimYoungHyun (youngh.kim@kt.com)
   * @return StringEncryptor
   */
  @Bean(name = "jasyptStringEncryptor")
  public StringEncryptor jasyptEncryptor() {
    PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();

    config.setPassword(KEY);
    config.setAlgorithm(ALGORITHM);
    config.setKeyObtentionIterations("1000");
    config.setPoolSize("1");
    config.setProviderName("SunJCE");
    config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
    config.setStringOutputType("base64");
    encryptor.setConfig(config);

    return encryptor;
  }

  /**
   *
   *
   * <pre>
   * 평문을 암호화한다.
   * </pre>
   *
   * @author KimYoungHyun (youngh.kim@kt.com)
   * @param value
   * @return String
   */
  public static String encrypt(String value) {
    StandardPBEStringEncryptor pbeEnc = new StandardPBEStringEncryptor();
    pbeEnc.setAlgorithm(ALGORITHM);
    pbeEnc.setPassword(KEY);

    return pbeEnc.encrypt(value);
  }
}
