org.nervousync.security.factory.SecureFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-jdk11 Show documentation
Show all versions of utils-jdk11 Show documentation
Java utility collections, development by Nervousync Studio (NSYC)
/*
* Licensed to the Nervousync Studio (NSYC) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nervousync.security.factory;
import org.nervousync.exceptions.crypto.CryptoException;
import org.nervousync.security.api.SecureAdapter;
import org.nervousync.utils.*;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.*;
/**
* Secure factory instance
*
* Running in singleton mode. Using for protect password in any configure files.
* Supported algorithm: RSA1024/RSA2048/SM2/AES128/AES192/AES256/DES/3DES/SM4
*
* 安全配置信息定义
* 使用单例模式运行。用于在任何配置文件中保护密码。支持的算法:RSA1024/RSA2048/SM2/AES128/AES192/AES256/DES/3DES/SM4
*
* @author Steven Wee [email protected]
* @version $Revision: 1.0.0 $ $Date: Jan 13, 2012 12:33:56 $
*/
public final class SecureFactory {
/**
* Logger instance
* 日志对象
*/
private static final LoggerUtils.Logger LOGGER = LoggerUtils.getLogger(SecureFactory.class);
/**
* Default certificate alias
* 默认证书别名
*/
private static final String SECURE_CERTIFICATE_ALIAS = "NSYC";
/**
* Default certificate password
* 默认证书库密码
*/
private static final String SECURE_CERTIFICATE_PASSWORD = "ns0528AO";
/**
* Root secure node
* 根安全节点
*/
private static SecureNode FACTORY_NODE = null;
/**
* Registered secure node mapping
* 已注册的安全节点映射
*/
private static final Map REGISTERED_NODE_MAP = new HashMap<>();
/**
* Private constructor method for SecureFactory
* 安全工厂的私有构造方法
*/
private SecureFactory() {
}
/**
* Check root secure node was configured
* 检查根安全节点是否配置成功
*
* @return Check result
* 检查结果
*/
public static boolean initialized() {
return FACTORY_NODE != null && FACTORY_NODE.isInitialized();
}
/**
* Configure root secure node using given secure config
* 使用给定的安全配置信息设置安全工厂的根安全节点
*
* @param secureConfig Secure config information
* 安全配置信息
*
* @return Initialize result
* 初始化结果
*/
public static boolean initialize(final SecureConfig secureConfig) {
return SecureNode.initFactory(secureConfig)
.filter(SecureNode::isInitialized)
.map(secureNode -> {
if (FACTORY_NODE != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Override_Factory_Config_Debug");
}
FACTORY_NODE = secureNode;
return Boolean.TRUE;
})
.orElse(Boolean.FALSE);
}
/**
* Check given secure algorithm was supported
* 检查给定的安全算法支持状态
*
* @param secureAlgorithm Secure algorithm
* 安全算法
*
* @return Check result
* 检查结果
*/
public static boolean supportedAlgorithm(final String secureAlgorithm) {
try {
SecureAlgorithm.valueOf(secureAlgorithm);
return Boolean.TRUE;
} catch (IllegalArgumentException e) {
return Boolean.FALSE;
}
}
/**
* Generate secure configure information using given secure algorithm
* 使用给定的安全算法生成安全配置信息实例对象
*
* @param secureAlgorithm Secure algorithm
* 安全算法
*
* @return Optional of SecureConfig instance
* Optional包装的安全配置信息实例对象
*/
public static Optional initConfig(final SecureAlgorithm secureAlgorithm) {
final byte[] keyBytes = generate(secureAlgorithm);
if (keyBytes.length == 0) {
LOGGER.error("Key_Bytes_Empty_Error");
return Optional.empty();
}
byte[] encBytes = initKey(keyBytes, Boolean.TRUE);
SecureConfig secureConfig = new SecureConfig();
secureConfig.setSecureAlgorithm(secureAlgorithm);
secureConfig.setSecureKey(StringUtils.base64Encode(encBytes));
return Optional.of(secureConfig);
}
/**
* Check given secure name was registered
* 检查给定的安全名称注册状态
*
* @param secureName Secure name
* 安全名称
* @return the boolean
*/
public static boolean registeredConfig(final String secureName) {
if (StringUtils.isEmpty(secureName) || FACTORY_NODE == null || !FACTORY_NODE.isInitialized()) {
return Boolean.FALSE;
}
return REGISTERED_NODE_MAP.containsKey(secureName);
}
/**
* Register secure config by given secure name and configure information instance
* 将给定的安全名称和安全配置信息实例注册到安全工厂
*
* @param secureName Secure name
* 安全名称
* @param secureConfig Secure config information
* 安全配置信息
*
* @return Register result
* 注册结果
*/
public static boolean register(final String secureName, final SecureConfig secureConfig) {
if (StringUtils.isEmpty(secureName) || FACTORY_NODE == null || !FACTORY_NODE.isInitialized()) {
return Boolean.FALSE;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Current Config: {}", secureConfig.toXML(Boolean.TRUE));
}
return SecureNode.initialize(secureConfig).filter(SecureNode::isInitialized)
.map(secureNode -> {
if (REGISTERED_NODE_MAP.containsKey(secureName)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Override secure config: {}", secureName);
}
}
REGISTERED_NODE_MAP.put(secureName, secureNode);
return Boolean.TRUE;
})
.orElse(Boolean.FALSE);
}
/**
* Deregister secure config by given secure name
* 将给定的安全名称取消注册
*
* @param secureName Secure name
* 安全名称
*/
public static void deregister(String secureName) {
if (StringUtils.notBlank(secureName)) {
REGISTERED_NODE_MAP.remove(secureName);
}
}
/**
* Update secure config protected password data
* 更新安全配置保护的密码信息
*
* @param dataContent Password data
* 密码信息
* @param originalName Original secure name
* 旧安全配置名称
* @param secureName New secure name
* 新安全配置名称
*
* @return Updated password data
* 更新后的密码信息
*/
public static String update(final String dataContent, final String originalName, final String secureName) {
if (StringUtils.isEmpty(dataContent)) {
return dataContent;
}
String string = decrypt(originalName, dataContent);
if (StringUtils.isEmpty(secureName)) {
return string;
} else {
return encrypt(secureName, string);
}
}
/**
* Encrypt data content using given secure name
* 使用给定的安全名称加密密码信息
*
* @param secureName New secure name
* 新安全配置名称
* @param dataContent Password data
* 密码信息
*
* @return Encrypted password data
* 加密后的密码信息
*/
public static String encrypt(final String secureName, final String dataContent) {
if (StringUtils.isEmpty(dataContent) || StringUtils.isEmpty(secureName) || !registeredConfig(secureName)) {
return dataContent;
}
return Optional.ofNullable(REGISTERED_NODE_MAP.get(secureName))
.map(secureNode -> secureNode.initCryptor(Boolean.TRUE))
.map(secureProvider -> {
try {
return StringUtils.base64Encode(secureProvider.finish(ConvertUtils.toByteArray(dataContent)));
} catch (CryptoException e) {
LOGGER.error("Encrypt_Data_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
return dataContent;
}
})
.orElse(dataContent);
}
/**
* Decrypt data content using given secure name
* 使用给定的安全名称解密密码信息
*
* @param secureName New secure name
* 新安全配置名称
* @param dataContent Password data
* 密码信息
*
* @return Decrypted password data
* 解密后的密码信息
*/
public static String decrypt(final String secureName, final String dataContent) {
if (StringUtils.isEmpty(dataContent) || StringUtils.isEmpty(secureName) || !registeredConfig(secureName)) {
return dataContent;
}
byte[] encBytes = StringUtils.base64Decode(dataContent);
if (encBytes.length == 0) {
return dataContent;
}
return Optional.ofNullable(REGISTERED_NODE_MAP.get(secureName))
.map(secureNode -> secureNode.initCryptor(Boolean.FALSE))
.map(secureProvider -> {
try {
return ConvertUtils.toString(secureProvider.finish(encBytes));
} catch (CryptoException e) {
LOGGER.error("Encrypt_Data_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
return dataContent;
}
})
.orElse(dataContent);
}
/**
* Initialize key bytes
* 初始化加密密钥数据
*
* @param dataBytes key bytes
* 加密密钥数据
* @param encrypt Encrypt status
* 加密密钥数据
*
* @return Initialized data bytes
* 初始化的数据
*/
private static byte[] initKey(final byte[] dataBytes, final boolean encrypt) {
if (FACTORY_NODE == null) {
return dataBytes;
}
SecureAdapter secureAdapter = FACTORY_NODE.initCryptor(encrypt);
if (secureAdapter == null) {
LOGGER.error("Security_Factory_Not_Initialized_Error");
return new byte[0];
}
try {
return secureAdapter.finish(dataBytes);
} catch (Exception e) {
return dataBytes;
}
}
/**
* Generate secure key by given secure algorithm
* 使用给定的安全算法生成安全密钥
*
* @param secureAlgorithm Secure algorithm
* 安全算法
*
* @return Generated key data bytes
* 生成的安全密钥数据
*/
private static byte[] generate(final SecureAlgorithm secureAlgorithm) {
switch (secureAlgorithm) {
case RSA1024:
return convertKeyPair(SecurityUtils.RSAKeyPair(1024), "SHA256withRSA");
case RSA2048:
return convertKeyPair(SecurityUtils.RSAKeyPair(2048), "SHA256withRSA");
case SM2:
return convertKeyPair(SecurityUtils.SM2KeyPair(), "SM3withSM2");
case AES128:
return SecurityUtils.AES128Key();
case AES192:
return SecurityUtils.AES192Key();
case AES256:
return SecurityUtils.AES256Key();
case DES:
return SecurityUtils.DESKey();
case TRIPLE_DES:
return SecurityUtils.TripleDESKey();
case SM4:
return SecurityUtils.SM4Key();
default:
return new byte[0];
}
}
/**
* Convert asymmetric key pair instance to secure key data bytes, using given signature algorithm
* 使用给定的签名算法将非对称密钥对实例对象转换为安全密钥数据
*
* @param keyPair Asymmetric key pair instance
* 非对称密钥对实例对象
* @param signAlgorithm Signature algorithm
* 签名算法
*
* @return Generated key data bytes
* 生成的安全密钥数据
*/
private static byte[] convertKeyPair(final KeyPair keyPair, final String signAlgorithm) {
long currentTime = DateTimeUtils.currentTimeMillis();
return CertificateUtils.PKCS12(keyPair, currentTime, new Date(currentTime),
new Date(currentTime + 365 * 24 * 60 * 60 * 1000L), SECURE_CERTIFICATE_ALIAS,
SECURE_CERTIFICATE_ALIAS, SECURE_CERTIFICATE_PASSWORD, null, signAlgorithm);
}
/**
* Secure Node
* 安全配置信息定义
*
* @author Steven Wee [email protected]
* @version $Revision: 1.0.0 $ $Date: Jan 13, 2012 12:38:45 $
*/
private static final class SecureNode {
/**
* Node initialize status
* 节点初始化状态
*/
private final boolean initialized;
/**
* Secure algorithm
* 安全算法
*/
private final SecureAlgorithm secureAlgorithm;
/**
* Secure key data bytes
* 安全密钥数据
*/
private final byte[] keyBytes;
/**
* Asymmetric private key
* 非对称加密私钥
*/
private final PrivateKey privateKey;
/**
* Asymmetric public key
* 非对称加密公钥
*/
private final PublicKey publicKey;
/**
* Constructor for SecureNode
* 安全节点构造方法
*
* @param secureAlgorithm Secure algorithm
* 安全算法
* @param dataBytes Secure key data bytes
* 安全密钥数据
*/
private SecureNode(final SecureAlgorithm secureAlgorithm, final byte[] dataBytes) {
this.secureAlgorithm = secureAlgorithm;
switch (this.secureAlgorithm) {
case RSA1024:
case RSA2048:
case SM2:
this.keyBytes = dataBytes;
KeyStore keyStore = CertificateUtils.loadKeyStore(dataBytes, SECURE_CERTIFICATE_PASSWORD);
if (keyStore == null) {
this.initialized = Boolean.FALSE;
this.privateKey = null;
this.publicKey = null;
} else {
this.publicKey =
Optional.ofNullable(CertificateUtils.x509(keyStore, SECURE_CERTIFICATE_ALIAS))
.map(Certificate::getPublicKey)
.orElse(null);
this.privateKey = CertificateUtils.privateKey(keyStore, SECURE_CERTIFICATE_ALIAS,
SECURE_CERTIFICATE_PASSWORD);
this.initialized = (this.publicKey != null && this.privateKey != null);
}
break;
case AES128:
case AES192:
case AES256:
case DES:
case TRIPLE_DES:
case SM4:
this.initialized = Boolean.TRUE;
this.keyBytes = dataBytes;
this.privateKey = null;
this.publicKey = null;
break;
default:
this.initialized = Boolean.FALSE;
this.keyBytes = null;
this.privateKey = null;
this.publicKey = null;
break;
}
}
/**
* Static method for initialize secure node by given secure config
* 静态方法用于使用给定的安全配置信息初始化安全节点实例
*
* @param secureConfig Secure config information
* 安全配置信息
*
* @return Optional of SecureNode instance
* Optional包装的安全节点实例对象
*/
public static Optional initialize(final SecureConfig secureConfig) {
if (secureConfig == null) {
return Optional.empty();
}
try {
return Optional.of(new SecureNode(secureConfig.getSecureAlgorithm(),
initKey(StringUtils.base64Decode(secureConfig.getSecureKey()), Boolean.FALSE)));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
/**
* Static method for initialize factory secure node by given secure config
* 静态方法用于使用给定的安全配置信息初始化根安全节点实例
*
* @param secureConfig Secure config information
* 安全配置信息
*
* @return Optional of SecureNode instance
* Optional包装的安全节点实例对象
*/
private static Optional initFactory(final SecureConfig secureConfig) {
if (secureConfig == null) {
return Optional.empty();
}
try {
return Optional.of(new SecureNode(secureConfig.getSecureAlgorithm(),
StringUtils.base64Decode(secureConfig.getSecureKey())));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
/**
* Initialize secure adapter
* 初始化加密解密适配器
*
* @param encrypt Encrypt status
* 加密状态
*
* @return Initialized adapter instance
* 初始化的适配器实例对象
*/
private SecureAdapter initCryptor(boolean encrypt) {
SecureAdapter secureAdapter = null;
if (this.initialized) {
try {
switch (this.secureAlgorithm) {
case RSA1024:
case RSA2048:
secureAdapter = encrypt ? SecurityUtils.RSAEncryptor(this.publicKey)
: SecurityUtils.RSADecryptor(this.privateKey);
break;
case SM2:
secureAdapter = encrypt ? SecurityUtils.SM2Encryptor(this.publicKey)
: SecurityUtils.SM2Decryptor(this.privateKey);
break;
case AES128:
case AES192:
case AES256:
secureAdapter = encrypt ? SecurityUtils.AESEncryptor(this.keyBytes)
: SecurityUtils.AESDecryptor(this.keyBytes);
break;
case DES:
secureAdapter = encrypt ? SecurityUtils.DESEncryptor(this.keyBytes)
: SecurityUtils.DESDecryptor(this.keyBytes);
break;
case TRIPLE_DES:
secureAdapter = encrypt ? SecurityUtils.TripleDESEncryptor(this.keyBytes)
: SecurityUtils.TripleDESDecryptor(this.keyBytes);
break;
case SM4:
secureAdapter = encrypt ? SecurityUtils.SM4Encryptor(this.keyBytes)
: SecurityUtils.SM4Decryptor(this.keyBytes);
break;
default:
break;
}
} catch (CryptoException e) {
LOGGER.error("Init_Crypto_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
}
return secureAdapter;
}
/**
* Getter method for Node initialize status
* 节点初始化状态的Getter方法
*
* @return Node initialize status
* 节点初始化状态
*/
public boolean isInitialized() {
return initialized;
}
}
/**
* Enumeration of Secure Algorithm
* 安全算法的枚举类
*
* @author Steven Wee [email protected]
* @version $Revision: 1.0.0 $ $Date: Jan 13, 2012 12:37:28 $
*/
public enum SecureAlgorithm {
RSA1024, RSA2048, SM2, AES128, AES192, AES256, DES, TRIPLE_DES, SM4
}
}