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

com.akeyless.auth.apikey.ApiKeyAuthenticator Maven / Gradle / Ivy

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


import java.io.UnsupportedEncodingException;
import java.security.*;

import com.akeyless.api.AkeylessApi;
import com.akeyless.auth.Authenticator;
import com.akeyless.auth.CredsRenewalException;
import com.akeyless.auth.swagger.model.SystemUserCredentialsReplyObj;
import com.akeyless.crypto.ecdsa.ECDSAUtils;
import com.akeyless.exceptions.AkeylessRuntimeException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class ApiKeyAuthenticator implements Authenticator {

    private final static int NONCE_LENGTH = 8;

    private AkeylessApi api;
    private byte[] prvKey;
    private String policyId;

    private SecureRandom random = new SecureRandom();

    public ApiKeyAuthenticator(AkeylessApi api, String policyId, String base64PrvKey) throws UnsupportedEncodingException {
        this.api = api;
        this.prvKey = Base64.decodeBase64(base64PrvKey.getBytes("UTF-8"));
        this.policyId = policyId;
    }

    private String stringToSign(String nonce, long sigTime) {
        return "signatureForTemporaryCredential;policy_id=" + policyId +
                ";nonce=" + nonce + ";time=" + Long.toString(sigTime);
    }

    public AuthApiSignature createApiSignature() throws AkeylessRuntimeException {
        String nonce = generateNonce();
        long sigTime = System.currentTimeMillis() / 1000L;
        String base64Sig;

        try {
            byte[] signature = ECDSAUtils.sign(stringToSign(nonce,sigTime) , this.prvKey, "P-256");
            base64Sig = new String(Base64.encodeBase64(signature));
        } catch (Exception e) {
            throw new AkeylessRuntimeException(e);
        }

        return new AuthApiSignature(base64Sig, nonce, sigTime);
    }

    private String generateNonce() {
        byte bytes[] = new byte[NONCE_LENGTH];
        random.nextBytes(bytes);
        return Hex.encodeHexString(bytes);
    }

    @Override
    public SystemUserCredentialsReplyObj authenticate() throws CredsRenewalException {
        AuthApiSignature sig = createApiSignature();
        try {
            return api.authenticateUAMApiKeyPolicy(policyId, sig.getSigTime(), sig.getNonce(),
                    sig.getSignature(),null, 0);
        } catch (Exception e) {
            throw new CredsRenewalException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy