package com.monkeylessey.framework.service.cipher;
|
|
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.context.annotation.Configuration;
|
import org.springframework.util.StringUtils;
|
|
import javax.crypto.BadPaddingException;
|
import javax.crypto.IllegalBlockSizeException;
|
import javax.crypto.NoSuchPaddingException;
|
import java.security.InvalidAlgorithmParameterException;
|
import java.security.InvalidKeyException;
|
import java.security.NoSuchAlgorithmException;
|
import java.util.function.Supplier;
|
|
@Configuration
|
@ConfigurationProperties(prefix = "cipher")
|
public abstract class DefaultCipherService implements CipherService,InitializingBean {
|
|
/**
|
* 用于生成密钥的字符串
|
*/
|
private String key;
|
|
/**
|
* 随机增强字符串
|
*/
|
private String iv;
|
|
@Override
|
public String decode(String cipherText) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
|
return decodeImpl(cipherText);
|
}
|
|
@Override
|
public String encode(String plainText) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
|
return encodeImpl(plainText);
|
}
|
|
/**
|
* 解密默认实现
|
* @return
|
*/
|
abstract public String decodeImpl(String cipherText) throws NoSuchPaddingException,
|
NoSuchAlgorithmException,
|
InvalidAlgorithmParameterException,
|
InvalidKeyException,
|
IllegalBlockSizeException,
|
BadPaddingException;
|
|
/**
|
* 加密默认实现
|
* @return
|
*/
|
abstract public String encodeImpl(String plainText) throws NoSuchPaddingException,
|
NoSuchAlgorithmException,
|
InvalidAlgorithmParameterException,
|
InvalidKeyException,
|
IllegalBlockSizeException,
|
BadPaddingException;
|
|
@Override
|
public void afterPropertiesSet() {
|
this.checkProperties(this::getKey, "请配置key");
|
this.checkProperties(this::getIv, "请配置iv");
|
}
|
|
/**
|
* 检查读取的配置
|
*
|
* @param getter
|
* @param errMsg
|
*/
|
public void checkProperties(Supplier<String> getter, String errMsg) {
|
if (StringUtils.isEmpty(getter.get())) {
|
throw new IllegalArgumentException(errMsg);
|
}
|
}
|
|
public String getKey() {
|
return key;
|
}
|
|
public void setKey(String key) {
|
this.key = key;
|
}
|
|
public String getIv() {
|
return iv;
|
}
|
|
public void setIv(String iv) {
|
this.iv = iv;
|
}
|
}
|