All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.akeyless.AkeylessUserImpl Maven / Gradle / Ivy

There is a newer version: 0.0.10
Show newest version
package com.akeyless;

import com.akeyless.api.AkeylessApi;
import com.akeyless.api.AkeylessApiImpl;
import com.akeyless.api.exceptions.*;
import com.akeyless.api.utils.DeriveKeyResult;
import com.akeyless.auth.Authenticator;
import com.akeyless.auth.CredsRenewal;
import com.akeyless.auth.apikey.ApiKeyAuthenticator;
import com.akeyless.caching.KeyOperationsCredsCache;
import com.akeyless.config.AkeylessUserConfiguration;
import com.akeyless.crypto.AkeylessCrypto;
import com.akeyless.crypto.exceptions.BadCiphertextException;
import com.akeyless.crypto.rsa.RSAUtils;
import com.akeyless.crypto.rsa.RsaMpcCrypt;
import com.akeyless.crypto.rsa.RsaMpcSign;
import com.akeyless.crypto.utils.AkeylessCiphertext;
import com.akeyless.crypto.utils.CryptoAlgorithm;
import com.akeyless.crypto.utils.Utils;
import com.akeyless.exceptions.AkeylessCryptoException;
import com.akeyless.exceptions.AkeylessRuntimeException;
import com.akeyless.uam.swagger.model.DerivationCredsReplyObj;
import com.akeyless.uam.swagger.model.GetItemReplyObj;
import com.akeyless.uam.swagger.model.GetUserItemsReplyObj;
import com.akeyless.uam.swagger.model.RSADecryptCredsReplyObj;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class AkeylessUserImpl implements AkeylessUser {

    protected AkeylessUserConfiguration config;
    protected AkeylessApi api;
    protected CredsRenewal credsRenewal;
    protected KeyOperationsCredsCache keyOperationsCredsCache;

    public AkeylessUserImpl(AkeylessUserConfiguration config) throws ApiCommunicationException, UnsupportedEncodingException {
        this.config = config;

        this.api = new AkeylessApiImpl(config);
        Authenticator authenticator = new ApiKeyAuthenticator(api, config.getPolicyId(), config.getPrvKeySeed());
        this.credsRenewal = new CredsRenewal(authenticator);
        this.keyOperationsCredsCache = new KeyOperationsCredsCache(api, credsRenewal);

    }

    @Override
    public AkeylessApi getApi() {
        return api;
    }

    @Override
    public CredsRenewal getCredsRenewal() {
        return credsRenewal;
    }

    @Override
    public String encryptString(final String keyName, final String plaintext)
            throws CredentialsNotFoundException, InvalidParamException, AkeylessCryptoException,
            MissingRequiredParamException, InvalidCredentialsException, NotFoundException,
            ApiCommunicationException {

        try {
            return encrypt(keyName, plaintext.getBytes(), null).toString();
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    @Override
    public String decryptString(final String keyName, final String ciphertext)
            throws ApiCommunicationException, AkeylessCryptoException, MissingRequiredParamException,
            InvalidCredentialsException, InvalidParamException, CredentialsNotFoundException,
            NotFoundException, BadCiphertextException {

        try {
            return new String(decrypt(keyName, Base64.decodeBase64(ciphertext.getBytes()), null));
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    @Override
    public byte[] encryptData(final String keyName, final byte[] plaintext, final byte[] aad)
            throws CredentialsNotFoundException, InvalidParamException, AkeylessCryptoException,
            MissingRequiredParamException, InvalidCredentialsException, NotFoundException,
            ApiCommunicationException {

        try {
            return encrypt(keyName, plaintext, aad).toByteArray();
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    @Override
    public byte[] decryptData(final String keyName, final byte[] ciphertext, final byte[] aad)
            throws ApiCommunicationException, AkeylessCryptoException, MissingRequiredParamException,
            InvalidCredentialsException, InvalidParamException, CredentialsNotFoundException,
            NotFoundException, BadCiphertextException {

        try {
            return decrypt(keyName, ciphertext, aad);
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    private AkeylessCiphertext encrypt(final String keyName, final byte[] plaintext, final byte[] aad)
            throws NotFoundException, InvalidParamException, CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException, AkeylessCryptoException, InvalidKeyException {

        DerivationCredsReplyObj derivationCreds = keyOperationsCredsCache.getKeyDerivationCreds(
                new KeyOperationsCredsCache.Key(keyName, 0, ""));

        CryptoAlgorithm alg = CryptoAlgorithm.getAlgByName(derivationCreds.getItemType());
        Integer keyVersion = derivationCreds.getItemVersion();

        int numOfFragments = derivationCreds.getKfMsHostsDNSMap().size();
        ArrayList derivationsData = new ArrayList<>(Collections.nCopies(numOfFragments,Utils.genDerivationData()));

        DeriveKeyResult deriveKeyRes = api.deriveKey(derivationCreds,
                credsRenewal.getKfmCreds(), derivationsData, alg.isDeterministic());

        return AkeylessCrypto.encrypt(alg, deriveKeyRes.getDerivedKey(),
                keyVersion, deriveKeyRes.getDerivationsData(), plaintext, aad);
    }

    private byte[] decrypt(final String keyName, final byte[] ciphertext, final byte[] aad)
            throws AkeylessRuntimeException, NotFoundException, InvalidParamException,
            CredentialsNotFoundException, InvalidCredentialsException, MissingRequiredParamException,
            ApiCommunicationException, AkeylessCryptoException, InvalidKeyException, BadCiphertextException {

        Integer keyVersion = AkeylessCiphertext.extractKeyVersionFromCipher(ciphertext);

        DerivationCredsReplyObj derivationCreds = keyOperationsCredsCache.getKeyDerivationCreds(
                new KeyOperationsCredsCache.Key(keyName, keyVersion, ""));

        int numOfFragments = derivationCreds.getKfMsHostsDNSMap().size();
        CryptoAlgorithm alg = CryptoAlgorithm.getAlgByName(derivationCreds.getItemType());
        AkeylessCiphertext cipher = new AkeylessCiphertext(alg, ciphertext);

        DeriveKeyResult deriveKeyRes = api.deriveKey(derivationCreds,
                credsRenewal.getKfmCreds(), cipher.getDerivationsData(numOfFragments), false);

        return AkeylessCrypto.decrypt(alg, cipher, deriveKeyRes.getDerivedKey(), aad);
    }

    @Override
    public byte[] decryptPKCS1v15(final String keyName, final byte[] ciphertext)
            throws NotFoundException, InvalidParamException, CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException, AkeylessCryptoException {

        RSADecryptCredsReplyObj rsaDecryptCreds = keyOperationsCredsCache.getRSAKeyDecryptCreds(
                new KeyOperationsCredsCache.Key(keyName, 0, ""));

        RSAPublicKey rsaPubKey = RSAUtils.extractPublicKeyFromBytes(Base64.decodeBase64(rsaDecryptCreds.getPublicValue()));

        List decryptResults = api.rsaFragmentDecrypt(rsaDecryptCreds,
                credsRenewal.getKfmCreds(), new String(Base64.encodeBase64(ciphertext)));

        try {
            return RsaMpcCrypt.postDecryptPKCS1v15(decryptResults, rsaPubKey.getModulus());
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        } catch (BadPaddingException e) {
            throw new AkeylessCryptoException(e);
        }
    }

    @Override
    public byte[] encryptPKCS1v15(final String keyName, final byte[] plaintext)
            throws NotFoundException, InvalidParamException, CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException, AkeylessCryptoException {

        RSADecryptCredsReplyObj rsaDecryptCreds = keyOperationsCredsCache.getRSAKeyDecryptCreds(
                new KeyOperationsCredsCache.Key(keyName, 0, ""));

        RSAPublicKey rsaPubKey = RSAUtils.extractPublicKeyFromBytes(Base64.decodeBase64(rsaDecryptCreds.getPublicValue()));

        try {
            Cipher encryptCipher = Cipher.getInstance("RSA");
            encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPubKey);
            return encryptCipher.doFinal(plaintext);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            throw new AkeylessCryptoException(e);
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    @Override
    public byte[] signPKCS1v15(final String keyName, final byte[] message)
            throws NotFoundException, InvalidParamException, CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException, AkeylessCryptoException {
        RSADecryptCredsReplyObj rsaDecryptCreds = keyOperationsCredsCache.getRSAKeyDecryptCreds(
                new KeyOperationsCredsCache.Key(keyName, 0, ""));

        RSAPublicKey rsaPubKey = RSAUtils.extractPublicKeyFromBytes(Base64.decodeBase64(rsaDecryptCreds.getPublicValue()));

        try {
            byte[] msgToSig = RsaMpcSign.preSignPKCS1v15(message, rsaPubKey.getModulus());

            List decryptResults = api.rsaFragmentDecrypt(rsaDecryptCreds,
                    credsRenewal.getKfmCreds(), new String(Base64.encodeBase64(msgToSig)));

            return RsaMpcSign.postSignPKCS1v15(decryptResults, rsaPubKey.getModulus());

        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        } catch (BadPaddingException | NoSuchAlgorithmException | IOException e) {
            throw new AkeylessCryptoException(e);
        }
    }

    @Override
    public boolean verifyPKCS1v15(final String keyName,
                          final byte[] message,
                          final byte[] signature
    ) throws NotFoundException, InvalidParamException, CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException, AkeylessCryptoException {

        RSADecryptCredsReplyObj rsaDecryptCreds = keyOperationsCredsCache.getRSAKeyDecryptCreds(
                new KeyOperationsCredsCache.Key(keyName, 0, ""));

        RSAPublicKey rsaPubKey = RSAUtils.extractPublicKeyFromBytes(Base64.decodeBase64(rsaDecryptCreds.getPublicValue()));

        try {
            Signature instance = Signature.getInstance("SHA256withRSA");
            instance.initVerify(rsaPubKey);
            instance.update(message);
            return instance.verify(signature);
        } catch (NoSuchAlgorithmException | SignatureException e) {
            throw new AkeylessCryptoException(e);
        } catch (InvalidKeyException e) {
            throw new AkeylessRuntimeException(e);
        }
    }

    @Override
    public GetItemReplyObj describeKey(String keyName) throws NotFoundException, InvalidParamException,
            CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException {
        return api.getItem(credsRenewal.getUamCreds(), keyName);
    }

    @Override
    public GetUserItemsReplyObj describeUserKeys() throws NotFoundException, InvalidParamException,
            CredentialsNotFoundException, InvalidCredentialsException,
            MissingRequiredParamException, ApiCommunicationException {
        return api.getUserItems(credsRenewal.getUamCreds());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy