FileTraceEncrypt.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.pdd.logger.filetrace;

  21. import java.security.Key;
  22. import java.util.HashMap;
  23. import java.util.Map;

  24. import org.apache.commons.lang.StringUtils;
  25. import org.apache.cxf.rs.security.jose.jwk.JsonWebKey;
  26. import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
  27. import org.apache.cxf.rs.security.jose.jwk.JwkUtils;
  28. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  29. import org.openspcoop2.protocol.sdk.Busta;
  30. import org.openspcoop2.protocol.sdk.Context;
  31. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  32. import org.openspcoop2.security.SecurityException;
  33. import org.openspcoop2.security.keystore.JWKSetStore;
  34. import org.openspcoop2.security.keystore.MerlinKeystore;
  35. import org.openspcoop2.security.keystore.PublicKeyStore;
  36. import org.openspcoop2.security.keystore.SecretKeyStore;
  37. import org.openspcoop2.security.keystore.SecretPasswordKeyDerivationConfig;
  38. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  39. import org.openspcoop2.utils.UtilsException;
  40. import org.openspcoop2.utils.certificate.JWK;
  41. import org.openspcoop2.utils.certificate.JWKSet;
  42. import org.openspcoop2.utils.certificate.KeyStore;
  43. import org.openspcoop2.utils.certificate.KeyUtils;
  44. import org.openspcoop2.utils.certificate.KeystoreType;
  45. import org.openspcoop2.utils.certificate.SymmetricKeyUtils;
  46. import org.openspcoop2.utils.certificate.byok.BYOKConfig;
  47. import org.openspcoop2.utils.certificate.byok.BYOKCostanti;
  48. import org.openspcoop2.utils.certificate.byok.BYOKManager;
  49. import org.openspcoop2.utils.certificate.byok.BYOKRequestParams;
  50. import org.openspcoop2.utils.io.Base64Utilities;
  51. import org.openspcoop2.utils.io.HexBinaryUtilities;
  52. import org.openspcoop2.utils.security.Encrypt;
  53. import org.openspcoop2.utils.security.EncryptOpenSSLPass;
  54. import org.openspcoop2.utils.security.EncryptOpenSSLPassPBKDF2;
  55. import org.openspcoop2.utils.security.EncryptWrapKey;
  56. import org.openspcoop2.utils.security.JOSESerialization;
  57. import org.openspcoop2.utils.security.JWEOptions;
  58. import org.openspcoop2.utils.security.JsonEncrypt;
  59. import org.openspcoop2.utils.security.JsonUtils;
  60. import org.openspcoop2.utils.security.JwtHeaders;
  61. import org.openspcoop2.utils.security.OpenSSLEncryptionMode;
  62. import org.slf4j.Logger;

  63. import com.nimbusds.jose.jwk.KeyUse;

  64. /**    
  65.  * FileTraceEncrypt
  66.  *
  67.  * @author Poli Andrea (poli@link.it)
  68.  * @author $Author$
  69.  * @version $Rev$, $Date$
  70.  */
  71. public class FileTraceEncrypt {

  72.     private Logger log;
  73.     private RequestInfo requestInfo;
  74.     private Context context;
  75.     private Busta busta;
  76.    
  77.     public FileTraceEncrypt(Logger log, RequestInfo requestInfo, Context context, Busta busta) {
  78.         this.log = log;
  79.         this.requestInfo = requestInfo;
  80.         this.context = context;
  81.         this.busta = busta;
  82.     }
  83.    
  84.     private static final String JAVA_SEPARATOR = ".";
  85.    
  86.     private String getKeystoreError(FileTraceEncryptConfig config) {
  87.         return "Access to keystore ["+config.getKeystoreType().getNome()+"] '"+config.getKeystorePath()+"' failed";
  88.     }
  89.     private String getKeyError(FileTraceEncryptConfig config) {
  90.         return "Access to key ["+config.getKeystoreType().getNome()+"] '"+config.getKeystorePath()+"' failed";
  91.     }

  92.     private static final String KEYSTORE_PREFIX = "Keystore [";
  93.    
  94.     public String encrypt(FileTraceEncryptConfig config,
  95.             String value) throws UtilsException {
  96.    
  97.         FileTraceEncryptKey fileTraceEncryptKey = new FileTraceEncryptKey();

  98.         boolean initPasswordKeyDerivation = false;
  99.         try {
  100.             switch (config.getKeystoreType()) {
  101.             case JKS:
  102.             case PKCS12:
  103.             case PKCS11:
  104.             case JCEKS:
  105.                 readKeystore(fileTraceEncryptKey, config);
  106.                 break;
  107.             case JWK_SET:
  108.                 readJwk(fileTraceEncryptKey, config);
  109.                 break;
  110.             case PUBLIC_KEY:
  111.                 readPublicKey(fileTraceEncryptKey, config);
  112.                 break;
  113.             case SYMMETRIC_KEY:
  114.                 readSecretKey(fileTraceEncryptKey, config);
  115.                 break;
  116.             case PASSWORD_KEY_DERIVATION:
  117.                 readPasswordKeyDerivation(fileTraceEncryptKey, config);
  118.                 initPasswordKeyDerivation = true;
  119.                 break;
  120.             default:
  121.                 throw new UtilsException(KEYSTORE_PREFIX+config.getKeystoreType().getNome()+"] unsupported");
  122.             }
  123.         }catch(Exception e) {
  124.             throw new UtilsException(e.getMessage(),e);
  125.         }
  126.        
  127.         /**System.out.println("CONF ["+config.getName()+"] java["+config.isJavaEngine()+"] jose["+config.isJoseEngine()+"]");*/
  128.         if(config.isJavaEngine()) {
  129.             if(config.isKeyWrap()) {
  130.                 if(initPasswordKeyDerivation) {
  131.                     throw new UtilsException(KEYSTORE_PREFIX+config.getKeystoreType().getNome()+"] unusable with key wrap java mode");
  132.                 }
  133.                 return encJavaKeyWrap(fileTraceEncryptKey, config, value);
  134.             }
  135.             else {
  136.                 return encJava(fileTraceEncryptKey, config, value);
  137.             }
  138.         }
  139.         else if(config.isJoseEngine()) {
  140.             if(initPasswordKeyDerivation) {
  141.                 throw new UtilsException(KEYSTORE_PREFIX+config.getKeystoreType().getNome()+"] unusable with jose mode");
  142.             }
  143.             return encJose(fileTraceEncryptKey, config, value);
  144.         }
  145.         else if(config.isOpenSSLEngine()) {
  146.             return encOpenSSL(fileTraceEncryptKey, config, value);
  147.         }
  148.         else {
  149.             throw new UtilsException("Encrypt mode undefined");
  150.         }
  151.        
  152.     }
  153.    
  154.     private BYOKRequestParams getBYOKRequestParams(FileTraceEncryptConfig config) throws UtilsException {
  155.         BYOKRequestParams req = null;
  156.         if(config!=null && config.getKmsId()!=null) {
  157.             BYOKManager manager = BYOKManager.getInstance();
  158.             if(manager==null) {
  159.                 throw new UtilsException("BYOKManager not initialized");
  160.             }
  161.             BYOKConfig bconfig = manager.getKMSConfigByType(config.getKmsId());
  162.             if(bconfig==null) {
  163.                 throw new UtilsException("BYOK configuration for kms id '"+config.getKmsId()+"' not found");
  164.             }
  165.             req = new BYOKRequestParams();
  166.             req.setConfig(bconfig);
  167.            
  168.             Map<String, String> inputMap = new HashMap<>();
  169.             if(config.getKmsInput()!=null && !config.getKmsInput().isEmpty()) {
  170.                 inputMap.putAll(config.getKmsInput());
  171.             }
  172.             req.setInputMap(inputMap);
  173.            
  174.             Map<String,Object> dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(this.busta, this.requestInfo, this.context, this.log);
  175.             req.setDynamicMap(dynamicMap);
  176.         }
  177.         return req;
  178.     }
  179.    
  180.     private void readKeystore(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  181.         String type = KeystoreType.PKCS11.equals(config.getKeystoreType()) ? config.getKeystoreHsmType() : config.getKeystoreType().getNome();
  182.         MerlinKeystore merlinKs = GestoreKeystoreCache.getMerlinKeystore(this.requestInfo,
  183.                 config.getKeystorePath(), type,
  184.                 config.getKeystorePassword(),
  185.                 getBYOKRequestParams(config));
  186.         if(merlinKs==null || merlinKs.getKeyStore()==null) {
  187.             throw new UtilsException(getKeystoreError(config));
  188.         }
  189.         fileTraceEncryptKey.ks = merlinKs.getKeyStore();
  190.         /**if(config.isJavaEngine()) {*/
  191.         // bisogna sapere se e' secret o meno
  192.         if(KeystoreType.JCEKS.equals(config.getKeystoreType())) {
  193.             fileTraceEncryptKey.key = fileTraceEncryptKey.ks.getSecretKey(config.getKeyAlias(), config.getKeyPassword());
  194.             fileTraceEncryptKey.secret = true;
  195.         }
  196.         else {
  197.             fileTraceEncryptKey.key = merlinKs.getKeyStore().getPublicKey(config.getKeyAlias());
  198.         }
  199.         /**}*/
  200.     }
  201.     private void readJwk(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  202.         JWKSetStore jwtStore = GestoreKeystoreCache.getJwkSetStore(this.requestInfo, config.getKeystorePath(),
  203.                 getBYOKRequestParams(config));
  204.         if(jwtStore==null || jwtStore.getJwkSet()==null) {
  205.             throw new UtilsException(getKeystoreError(config));
  206.         }
  207.         fileTraceEncryptKey.jsonWebKeys = jwtStore.getJwkSet().getJsonWebKeys();
  208.         /**if(config.isJavaEngine()) {*/
  209.         // bisogna sapere se e' secret o meno
  210.         JsonWebKey jwk = JsonUtils.readKey(fileTraceEncryptKey.jsonWebKeys, config.getKeyAlias());
  211.         if(jwk==null) {
  212.             throw new UtilsException("Accesso al keystore ["+config.getKeystoreType().getNome()+"] '"+config.getKeystorePath()+"' non riuscito per l'alias '"+config.getKeyAlias()+"'");
  213.         }
  214.         if(jwk.getAlgorithm()==null) {
  215.             jwk.setAlgorithm(config.isJavaEngine() ? "A256GCM" : config.getContentAlgorithm());
  216.         }
  217.         if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_RSA)) {
  218.             fileTraceEncryptKey.key = JwkUtils.toRSAPublicKey(jwk);
  219.         }
  220.         else if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_EC)) {
  221.             fileTraceEncryptKey.key = JwkUtils.toECPublicKey(jwk);
  222.         }
  223.         else {
  224.             fileTraceEncryptKey.key = JwkUtils.toSecretKey(jwk);
  225.             fileTraceEncryptKey.secret = true;
  226.         }
  227.         /**}*/
  228.     }
  229.    
  230.     private byte[] readKeyInline(FileTraceEncryptConfig config) throws SecurityException {
  231.         String keyInLine = config.getKeyInline();
  232.         byte [] key = null;
  233.         if(config.isKeyBase64Encoding()) {
  234.             key = Base64Utilities.decode(keyInLine.getBytes());
  235.         }
  236.         else if(config.isKeyHexEncoding()) {
  237.             try {
  238.                 key = HexBinaryUtilities.decode(keyInLine);
  239.             }catch(Exception e) {
  240.                 throw new SecurityException(e.getMessage());
  241.             }
  242.         }
  243.         else {
  244.             key = keyInLine.getBytes();
  245.         }
  246.         return key;
  247.     }
  248.     private byte[] readEncodedKeyFromPath(FileTraceEncryptConfig config) throws SecurityException {
  249.         byte [] encodedKey = GestoreKeystoreCache.getExternalResource(this.requestInfo, config.getKeyPath(), null).getResource();
  250.         byte [] key = null;
  251.         if(config.isKeyBase64Encoding()) {
  252.             key = Base64Utilities.decode(encodedKey);
  253.         }
  254.         else {
  255.             try {
  256.                 key = HexBinaryUtilities.decode(new String(encodedKey));
  257.             }catch(Exception e) {
  258.                 throw new SecurityException(e.getMessage());
  259.             }
  260.         }
  261.         return key;
  262.     }
  263.    
  264.     private String readPublicKeyAlgo(FileTraceEncryptConfig config) {
  265.         String algo = config.getKeyAlgorithm();
  266.         if(config.isJoseEngine() || config.isKeyWrap()) {
  267.             if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_RSA)) {
  268.                 algo = KeyUtils.ALGO_RSA;
  269.             }
  270.             else if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_DSA)) {
  271.                 algo = KeyUtils.ALGO_DSA;
  272.             }
  273.             else if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_DH)) {
  274.                 algo = KeyUtils.ALGO_DH;
  275.             }
  276.             else if(config.getKeyAlgorithm().contains(KeyUtils.ALGO_EC)) {
  277.                 algo = KeyUtils.ALGO_EC;
  278.             }
  279.             else {
  280.                 algo = KeyUtils.ALGO_RSA;
  281.             }
  282.         }
  283.         return algo;
  284.     }
  285.     private void readPublicKey(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  286.         String algo = readPublicKeyAlgo(config);
  287.        
  288.         PublicKeyStore publicKeyStore = null;
  289.         if(config.getKeyInline()!=null && StringUtils.isNotEmpty(config.getKeyInline())) {
  290.             byte [] key = readKeyInline(config);
  291.             publicKeyStore = GestoreKeystoreCache.getPublicKeyStore(this.requestInfo, key, algo);
  292.         }
  293.         else {
  294.             if(config.isKeyBase64Encoding() || config.isKeyHexEncoding()) {
  295.                 byte [] key = readEncodedKeyFromPath(config);
  296.                 publicKeyStore = GestoreKeystoreCache.getPublicKeyStore(this.requestInfo, key, algo);
  297.             }
  298.             else {
  299.                 publicKeyStore = GestoreKeystoreCache.getPublicKeyStore(this.requestInfo, config.getKeyPath(), algo);
  300.             }
  301.         }
  302.         if(publicKeyStore==null) {
  303.             throw new UtilsException(getKeyError(config));
  304.         }
  305.         fileTraceEncryptKey.key = publicKeyStore.getPublicKey();
  306.         if(config.isJoseEngine()) {
  307.             if(config.getKeyId()!=null && StringUtils.isNotEmpty(config.getKeyId())) {
  308.                 config.setKeyAlias(config.getKeyId());
  309.             }
  310.             else {
  311.                 config.generateKeyAlias();
  312.             }
  313.             JWK jwk = new JWK(publicKeyStore.getPublicKey(), config.getKeyAlias());
  314.             JWKSet jwkSet = new JWKSet();
  315.             jwkSet.addJwk(jwk);
  316.             jwkSet.getJson(); // rebuild
  317.             fileTraceEncryptKey.jsonWebKeys = jwkSet.getJsonWebKeys();
  318.         }
  319.     }
  320.     private void readSecretKey(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  321.         String algo = config.isJoseEngine() ? SymmetricKeyUtils.ALGO_AES : config.getKeyAlgorithm();
  322.         SecretKeyStore secretKeyStore = null;
  323.         if(config.getKeyInline()!=null && StringUtils.isNotEmpty(config.getKeyInline())) {
  324.             byte [] key = readKeyInline(config);
  325.             secretKeyStore = GestoreKeystoreCache.getSecretKeyStore(this.requestInfo, key, algo,
  326.                     getBYOKRequestParams(config));
  327.         }
  328.         else {
  329.             if(config.isKeyBase64Encoding() || config.isKeyHexEncoding()) {
  330.                 byte [] key = readEncodedKeyFromPath(config);
  331.                 secretKeyStore = GestoreKeystoreCache.getSecretKeyStore(this.requestInfo, key, algo,
  332.                         getBYOKRequestParams(config));
  333.             }
  334.             else {
  335.                 secretKeyStore = GestoreKeystoreCache.getSecretKeyStore(this.requestInfo, config.getKeyPath(), algo,
  336.                         getBYOKRequestParams(config));
  337.             }
  338.         }
  339.         initSecretKey(secretKeyStore, fileTraceEncryptKey, config);
  340.     }
  341.     private void readPasswordKeyDerivation(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  342.         fileTraceEncryptKey.pwdKeyDerivationConfig = new SecretPasswordKeyDerivationConfig(config.getPassword(), config.getPasswordType(), config.getPasswordIteration());
  343.         if(!config.isOpenSSLEngine() ) {
  344.             SecretKeyStore secretKeyStore = GestoreKeystoreCache.getSecretKeyStore(this.requestInfo, fileTraceEncryptKey.pwdKeyDerivationConfig,
  345.                     getBYOKRequestParams(config));
  346.             initSecretKey(secretKeyStore, fileTraceEncryptKey, config);
  347.         }
  348.     }
  349.     private void initSecretKey(SecretKeyStore secretKeyStore, FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config) throws UtilsException, SecurityException {
  350.         if(secretKeyStore==null) {
  351.             throw new UtilsException(getKeyError(config));
  352.         }
  353.         fileTraceEncryptKey.key = secretKeyStore.getSecretKey();
  354.         fileTraceEncryptKey.iv = secretKeyStore.getIv();
  355.         fileTraceEncryptKey.salt = secretKeyStore.getSalt();
  356.         fileTraceEncryptKey.secret = true;
  357.         if(config.isJoseEngine()) {
  358.             if(config.getKeyId()!=null && StringUtils.isNotEmpty(config.getKeyId())) {
  359.                 config.setKeyAlias(config.getKeyId());
  360.             }
  361.             else {
  362.                 config.generateKeyAlias();
  363.             }
  364.             JWK jwk = new JWK(secretKeyStore.getSecretKey(), config.getKeyAlias(), KeyUse.ENCRYPTION);
  365.             JWKSet jwkSet = new JWKSet();
  366.             jwkSet.addJwk(jwk);
  367.             jwkSet.getJson(); // rebuild
  368.             fileTraceEncryptKey.jsonWebKeys = jwkSet.getJsonWebKeys();
  369.         }
  370.     }
  371.    
  372.     private String encJava(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  373.        
  374.         Encrypt encrypt = null;
  375.         if(fileTraceEncryptKey.secret &&
  376.                 fileTraceEncryptKey.iv!=null) {
  377.             encrypt = new Encrypt(fileTraceEncryptKey.key, fileTraceEncryptKey.iv);
  378.         }
  379.         else {
  380.             encrypt = new Encrypt(fileTraceEncryptKey.key);
  381.         }
  382.        
  383.         if(fileTraceEncryptKey.secret &&
  384.                 fileTraceEncryptKey.iv==null) {
  385.             encrypt.initIV(config.getContentAlgorithm());
  386.         }
  387.        
  388.         byte [] encrypted = null;
  389.         try {
  390.             /**System.out.println("encrypt ["+config.getContentAlgorithm()+"]...");*/
  391.             encrypted = encrypt.encrypt(value.getBytes(), config.getContentAlgorithm());
  392.             /**System.out.println("encrypt ok");*/
  393.         }catch(Exception e) {
  394.             /**System.out.println("encrypt ERROR: "+e.getMessage());*/
  395.             throw new UtilsException(e.getMessage(),e);
  396.         }
  397.        
  398.         if(fileTraceEncryptKey.secret &&
  399.                 fileTraceEncryptKey.salt!=null){
  400.             encrypted = EncryptOpenSSLPass.formatOutput(fileTraceEncryptKey.salt, encrypted);
  401.         }
  402.        
  403.         String en = null;
  404.         if(config.isBase64Encoding()) {
  405.             en = Base64Utilities.encodeAsString(encrypted);
  406.         }
  407.         else if(config.isHexEncoding()) {
  408.             en = HexBinaryUtilities.encodeAsString(encrypted);
  409.         }
  410.         else {
  411.             throw new UtilsException("Java algorithm undefined in keystore ["+config.getKeystoreType().getNome()+"] '"+config.getKeystorePath()+"'");
  412.         }
  413.         if(fileTraceEncryptKey.secret) {
  414.             if(config.isBase64Encoding()) {
  415.                 return encrypt.getIVBase64AsString()+JAVA_SEPARATOR+en;
  416.             }
  417.             else {
  418.                 return encrypt.getIVHexBinaryAsString()+JAVA_SEPARATOR+en;
  419.             }
  420.         }
  421.         return en;
  422.     }
  423.    
  424.     private String encJavaKeyWrap(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  425.        
  426.         EncryptWrapKey encrypt = null;
  427.         if(fileTraceEncryptKey.ks!=null) {
  428.             encrypt = new EncryptWrapKey(fileTraceEncryptKey.ks, config.getKeyAlias());
  429.         }
  430.         else {
  431.             encrypt = new EncryptWrapKey(fileTraceEncryptKey.key);
  432.         }
  433.                
  434.         byte [] encrypted = null;
  435.         try {
  436.             /**System.out.println("encrypt ["+config.getKeyAlgorithm()+"] ["+config.getContentAlgorithm()+"]...");*/
  437.             encrypted = encrypt.encrypt(value.getBytes(), config.getKeyAlgorithm(), config.getContentAlgorithm());
  438.             /**System.out.println("encrypt ok");*/
  439.         }catch(Exception e) {
  440.             /**System.out.println("encrypt ERROR: "+e.getMessage());*/
  441.             throw new UtilsException(e.getMessage(),e);
  442.         }
  443.        
  444.         String en = null;
  445.         if(config.isBase64Encoding()) {
  446.             en = Base64Utilities.encodeAsString(encrypted);
  447.         }
  448.         else if(config.isHexEncoding()) {
  449.             en = HexBinaryUtilities.encodeAsString(encrypted);
  450.         }
  451.         else {
  452.             throw new UtilsException("Java algorithm undefined in keystore ["+config.getKeystoreType().getNome()+"] '"+config.getKeystorePath()+"'");
  453.         }

  454.         if(config.isBase64Encoding()) {
  455.             return encrypt.getWrappedKeyBase64()+JAVA_SEPARATOR+encrypt.getIVBase64AsString()+JAVA_SEPARATOR+en;
  456.         }
  457.         else {
  458.             return encrypt.getWrappedKeyHexBinary()+JAVA_SEPARATOR+encrypt.getIVHexBinaryAsString()+JAVA_SEPARATOR+en;
  459.         }
  460.        
  461.     }
  462.    
  463.     private String encJose(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  464.         JsonEncrypt encrypt = null;
  465.         JwtHeaders jwtHeaders = null;
  466.         JWEOptions options = new JWEOptions(JOSESerialization.COMPACT);
  467.         if(fileTraceEncryptKey.ks!=null) {
  468.             jwtHeaders = config.getJwtHeaders(fileTraceEncryptKey.ks);
  469.             if(fileTraceEncryptKey.secret) {
  470.                 encrypt = new JsonEncrypt(fileTraceEncryptKey.ks, config.getKeyAlias(), config.getKeyPassword(), config.getKeyAlgorithm(), config.getContentAlgorithm(),
  471.                         jwtHeaders, options);
  472.             }
  473.             else {
  474.                 encrypt = new JsonEncrypt(fileTraceEncryptKey.ks, config.getKeyAlias(), config.getKeyAlgorithm(), config.getContentAlgorithm(),
  475.                         jwtHeaders, options);
  476.             }
  477.         }
  478.         else {
  479.             jwtHeaders = config.getJwtHeaders(fileTraceEncryptKey.jsonWebKeys);
  480.             encrypt = new JsonEncrypt(fileTraceEncryptKey.jsonWebKeys, fileTraceEncryptKey.secret, config.getKeyAlias(), config.getKeyAlgorithm(), config.getContentAlgorithm(),
  481.                     jwtHeaders, options);
  482.         }
  483.         return encrypt.encrypt(value);
  484.     }
  485.    
  486.     private String encOpenSSL(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  487.         if(BYOKCostanti.isOpenSSLPBKDF2PasswordDerivationKeyMode(fileTraceEncryptKey.pwdKeyDerivationConfig.getPasswordEncryptionMode())) {
  488.             return encOpenSSLPBKDF2(fileTraceEncryptKey, config, value);
  489.         }
  490.         else {
  491.             return encOpenSSLStandard(fileTraceEncryptKey, config, value);
  492.         }
  493.     }
  494.     private String encOpenSSLStandard(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  495.        
  496.         SecretPasswordKeyDerivationConfig passwordKeyDerivationConfig = fileTraceEncryptKey.pwdKeyDerivationConfig;
  497.        
  498.         EncryptOpenSSLPass encrypt = new EncryptOpenSSLPass(passwordKeyDerivationConfig.getPassword(),
  499.                 OpenSSLEncryptionMode.toMode(passwordKeyDerivationConfig.getPasswordEncryptionMode()));
  500.        
  501.         if(config.isBase64Encoding()) {
  502.             return encrypt.encryptBase64AsString(value.getBytes());
  503.         }
  504.         else if(config.isHexEncoding()) {
  505.             return encrypt.encryptHexBinaryAsString(value.getBytes());
  506.         }
  507.         else {
  508.             throw new UtilsException("Encoding mode undefined");
  509.         }
  510.     }
  511.     private String encOpenSSLPBKDF2(FileTraceEncryptKey fileTraceEncryptKey, FileTraceEncryptConfig config, String value) throws UtilsException {
  512.        
  513.         SecretPasswordKeyDerivationConfig passwordKeyDerivationConfig = fileTraceEncryptKey.pwdKeyDerivationConfig;
  514.        
  515.         EncryptOpenSSLPassPBKDF2 encrypt = new EncryptOpenSSLPassPBKDF2(passwordKeyDerivationConfig.getPassword(),
  516.                 passwordKeyDerivationConfig.getPasswordIterator(),
  517.                 OpenSSLEncryptionMode.toMode(passwordKeyDerivationConfig.getPasswordEncryptionMode()));
  518.        
  519.         if(config.isBase64Encoding()) {
  520.             return encrypt.encryptBase64AsString(value.getBytes());
  521.         }
  522.         else if(config.isHexEncoding()) {
  523.             return encrypt.encryptHexBinaryAsString(value.getBytes());
  524.         }
  525.         else {
  526.             throw new UtilsException("Encoding mode undefined");
  527.         }
  528.     }
  529. }

  530. class FileTraceEncryptKey{
  531.     Key key = null;
  532.     byte[]iv = null;
  533.     byte[]salt = null;
  534.     boolean secret = false;
  535.     KeyStore ks = null;
  536.     JsonWebKeys jsonWebKeys = null;
  537.     SecretPasswordKeyDerivationConfig pwdKeyDerivationConfig = null;
  538. }