Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

/** Creates a self signed certificate. */
private X509Certificate getSelfCertificate(String alias, long validity, KeyPair keyPair) throws Exception {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);
    final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(new X500Principal(alias),
            BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Principal(alias),
            keyPair.getPublic());
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA1withRSA");
    contentSignerBuilder.setProvider("BC");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner));
}

From source file:com.poscoict.license.service.BoardService.java

public Map<String, Object> passwordPop(HttpSession session) throws Exception {
    logger.info("get passwordPopForm");
    Map<String, Object> map = new HashMap<String, Object>();

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);//from w ww .ja va 2  s  .  c  o  m

    KeyPair keyPair = generator.genKeyPair();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // ? ? ??  ? .
    session.setAttribute("__rsaPrivateKey__", privateKey);

    //  ?  JavaScript RSA ?? .
    RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);

    map.put("publicKeyModulus", publicSpec.getModulus().toString(16));
    map.put("publicKeyExponent", publicSpec.getPublicExponent().toString(16));
    logger.info("return passwordPopForm");
    return map;
}

From source file:it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java

/**
 * Esegue l&rsquo;operazione.//www  . j av  a2  s. c  o  m
 */
public void run() {
    Properties props;
    OutputStream publicOut = null;
    OutputStream privateOut = null;
    KeyPair keyPair;
    KeyPairGenerator keyGen;

    if (myConfigFile == null) {
        throw new PropertyNotSetException(toString(), "configFile");
    }
    if (myPublicFile == null) {
        throw new PropertyNotSetException(toString(), "publicFile");
    }
    if (myPrivateFile == null) {
        throw new PropertyNotSetException(toString(), "privateFile");
    }

    try {
        props = loadConfig();
        publicOut = openOutput(myPublicFile);
        if (publicOut == null) {
            return;
        }
        privateOut = openOutput(myPrivateFile);
        if (privateOut == null) {
            return;
        }

        keyGen = CryptoUtils.getKeyPairGenerator(props, myPrefix);
        keyPair = keyGen.generateKeyPair();

        props = CryptoUtils.toProperties(keyPair.getPublic(), myEncoded);
        props.store(publicOut, null);

        props = CryptoUtils.toProperties(keyPair.getPrivate(), myEncoded);
        props.store(privateOut, null);
    } catch (IOException ex) {
        throw new IOOperationException(ex);
    } finally {
        if (publicOut != null) {
            IOUtils.close(publicOut);
            publicOut = null;
        }
        if (privateOut != null) {
            IOUtils.close(privateOut);
            privateOut = null;
        }
    }
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

@Restrict("#{s:hasPermission('configuration', 'access')}")
public String generateCSR(String fileName) {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from   w w  w.  j av  a 2  s.c o m*/

    KeyPair pair = getKeyPair(fileName);
    boolean result = false;
    if (pair != null) {
        String url = applicationConfiguration.getIdpUrl().replaceFirst(".*//", "");
        String csrPrincipal = String.format("CN=%s", url);
        X500Principal principal = new X500Principal(csrPrincipal);

        PKCS10CertificationRequest csr = null;
        try {
            csr = new PKCS10CertificationRequest("SHA1withRSA", principal, pair.getPublic(), null,
                    pair.getPrivate());
        } catch (GeneralSecurityException e) {
            log.error(e.getMessage(), e);
            return OxTrustConstants.RESULT_FAILURE;
        }

        // Form download responce
        StringBuilder response = new StringBuilder();

        response.append(BEGIN_CERT_REQ + "\n");
        response.append(WordUtils.wrap(new String(Base64.encode(csr.getDEREncoded())), 64, "\n", true) + "\n");
        response.append(END_CERT_REQ + "\n");

        result = ResponseHelper.downloadFile("csr.pem", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN,
                response.toString().getBytes(), facesContext);
    }

    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}

From source file:com.netscape.cmstools.CRMFPopClient.java

public CertRequest createCertRequest(boolean self_sign, CryptoToken token, X509Certificate transportCert,
        String algorithm, KeyPair keyPair, Name subject, KeyWrapAlgorithm keyWrapAlgorithm) throws Exception {

    CertTemplate certTemplate = createCertTemplate(subject, keyPair.getPublic());

    SEQUENCE seq = new SEQUENCE();

    if (transportCert != null) { // add key archive Option
        byte[] iv = CryptoUtil.getNonceData(keyWrapAlgorithm.getBlockSize());
        OBJECT_IDENTIFIER kwOID = CryptoUtil.getOID(keyWrapAlgorithm);

        /* TODO(alee)//www.ja  v  a  2s .  com
         *
         * HACK HACK!
         * algorithms like AES KeyWrap do not require an IV, but we need to include one
         * in the AlgorithmIdentifier above, or the creation and parsing of the
         * PKIArchiveOptions options will fail.  So we include an IV in aid, but null it
         * later to correctly encrypt the data
         */
        AlgorithmIdentifier aid = new AlgorithmIdentifier(kwOID, new OCTET_STRING(iv));

        Class<?>[] iv_classes = keyWrapAlgorithm.getParameterClasses();
        if (iv_classes == null || iv_classes.length == 0)
            iv = null;

        WrappingParams params = getWrappingParams(keyWrapAlgorithm, iv);

        PKIArchiveOptions opts = CryptoUtil.createPKIArchiveOptions(token, transportCert.getPublicKey(),
                (PrivateKey) keyPair.getPrivate(), params, aid);

        seq.addElement(new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opts));
    } // key archival option

    /*
    OCTET_STRING ostr = createIDPOPLinkWitness();
    seq.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr));
    */

    if (self_sign) { // per rfc 5272
        System.out.println("CRMFPopClient: self_sign true. Generating SubjectKeyIdentifier extension.");
        KeyIdentifier subjKeyId = CryptoUtil.createKeyIdentifier(keyPair);
        OBJECT_IDENTIFIER oid = new OBJECT_IDENTIFIER(PKIXExtensions.SubjectKey_Id.toString());
        SEQUENCE extns = new SEQUENCE();
        extns.addElement(new AVA(oid, new OCTET_STRING(subjKeyId.getIdentifier())));
        certTemplate.setExtensions(extns);
    }

    return new CertRequest(new INTEGER(1), certTemplate, seq);
}

From source file:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java

/**
 * Prepare activation with given parameters
 *
 * @param userId                         User ID
 * @param maxFailedCount                 Maximum failed attempt count (5)
 * @param activationExpireTimestamp      Timestamp after which activation can no longer be completed
 * @param identity                       A string representing the provided identity
 * @param activationOtp                  Activation OTP parameter
 * @param activationNonceBase64          Activation nonce encoded as Base64
 * @param clientEphemeralPublicKeyBase64 Client ephemeral public key encoded as Base64
 * @param cDevicePublicKeyBase64         Encrypted device public key encoded as Base64
 * @param activationName                 Activation name
 * @param extras                         Extra parameter
 * @param applicationKey                 Application key
 * @param applicationSignature           Application signature
 * @param keyConversionUtilities         Utility class for key conversion
 * @return Prepared activation information
 * @throws GenericServiceException      In case invalid data is provided
 * @throws InvalidKeySpecException      If invalid key was provided
 * @throws InvalidKeyException          If invalid key was provided
 * @throws UnsupportedEncodingException If UTF-8 is not supported on the system
 *///from w  w w  . ja  v  a 2 s.c o  m
public CreateActivationResponse createActivation(String applicationKey, String userId, Long maxFailedCount,
        Date activationExpireTimestamp, String identity, String activationOtp, String activationNonceBase64,
        String clientEphemeralPublicKeyBase64, String cDevicePublicKeyBase64, String activationName,
        String extras, String applicationSignature, CryptoProviderUtil keyConversionUtilities)
        throws GenericServiceException, InvalidKeySpecException, InvalidKeyException,
        UnsupportedEncodingException {

    // Get current timestamp
    Date timestamp = new Date();

    ApplicationVersionEntity applicationVersion = applicationVersionRepository
            .findByApplicationKey(applicationKey);
    // if there is no such application, exit
    if (applicationVersion == null || applicationVersion.getSupported() == false) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    ApplicationEntity application = applicationVersion.getApplication();
    // if there is no such application, exit
    if (application == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Create an activation record and obtain the activation database record
    InitActivationResponse initActivationResponse = this.initActivation(application.getId(), userId,
            maxFailedCount, activationExpireTimestamp, keyConversionUtilities);
    ActivationRecordEntity activation = powerAuthRepository
            .findFirstByActivationId(initActivationResponse.getActivationId());

    // Get master private key
    String masterPrivateKeyBase64 = activation.getMasterKeyPair().getMasterKeyPrivateBase64();
    byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterPrivateKeyBase64);
    PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes);

    // Get client ephemeral public key
    PublicKey clientEphemeralPublicKey = null;
    if (clientEphemeralPublicKeyBase64 != null) { // additional encryption is used
        byte[] clientEphemeralPublicKeyBytes = BaseEncoding.base64().decode(clientEphemeralPublicKeyBase64);
        clientEphemeralPublicKey = keyConversionUtilities
                .convertBytesToPublicKey(clientEphemeralPublicKeyBytes);
    }

    // Decrypt the device public key
    byte[] C_devicePublicKey = BaseEncoding.base64().decode(cDevicePublicKeyBase64);
    byte[] activationNonce = BaseEncoding.base64().decode(activationNonceBase64);
    PublicKey devicePublicKey = powerAuthServerActivation.decryptDevicePublicKey(C_devicePublicKey, identity,
            masterPrivateKey, clientEphemeralPublicKey, activationOtp, activationNonce);

    if (devicePublicKey == null) { // invalid key was sent, return error
        activation.setActivationStatus(
                io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.REMOVED);
        powerAuthRepository.save(activation);
        callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
                activation.getActivationId());
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_NOT_FOUND);
    }

    byte[] applicationSignatureBytes = BaseEncoding.base64().decode(applicationSignature);

    if (!powerAuthServerActivation.validateApplicationSignature(identity, activationNonce, C_devicePublicKey,
            BaseEncoding.base64().decode(applicationKey),
            BaseEncoding.base64().decode(applicationVersion.getApplicationSecret()),
            applicationSignatureBytes)) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Update and persist the activation record
    activation.setActivationStatus(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED);
    activation.setDevicePublicKeyBase64(
            BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(devicePublicKey)));
    activation.setActivationName(activationName);
    activation.setExtras(extras);
    powerAuthRepository.save(activation);
    callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
            activation.getActivationId());

    // Generate response data
    byte[] activationNonceServer = powerAuthServerActivation.generateActivationNonce();
    String serverPublicKeyBase64 = activation.getServerPublicKeyBase64();
    PublicKey serverPublicKey = keyConversionUtilities
            .convertBytesToPublicKey(BaseEncoding.base64().decode(serverPublicKeyBase64));
    KeyPair ephemeralKeyPair = new KeyGenerator().generateKeyPair();
    PrivateKey ephemeralPrivateKey = ephemeralKeyPair.getPrivate();
    PublicKey ephemeralPublicKey = ephemeralKeyPair.getPublic();
    byte[] ephemeralPublicKeyBytes = keyConversionUtilities.convertPublicKeyToBytes(ephemeralPublicKey);

    // Encrypt the public key
    byte[] C_serverPublicKey = powerAuthServerActivation.encryptServerPublicKey(serverPublicKey,
            devicePublicKey, ephemeralPrivateKey, activationOtp, identity, activationNonceServer);

    // Get encrypted public key signature
    byte[] C_serverPubKeySignature = powerAuthServerActivation
            .computeServerDataSignature(activation.getActivationId(), C_serverPublicKey, masterPrivateKey);
    if (C_serverPubKeySignature == null) { // in case there is a technical error with signing and null is returned, return random bytes
        C_serverPubKeySignature = new KeyGenerator().generateRandomBytes(71);
    }

    // Compute the response
    CreateActivationResponse response = new CreateActivationResponse();
    response.setActivationId(activation.getActivationId());
    response.setActivationNonce(BaseEncoding.base64().encode(activationNonceServer));
    response.setEncryptedServerPublicKey(BaseEncoding.base64().encode(C_serverPublicKey));
    response.setEncryptedServerPublicKeySignature(BaseEncoding.base64().encode(C_serverPubKeySignature));
    response.setEphemeralPublicKey(BaseEncoding.base64().encode(ephemeralPublicKeyBytes));

    return response;
}

From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionTest.java

@Test
public void test05RevokeCert() throws Exception {
    addUser();/*from w  w  w.j  a v  a  2s .c o m*/

    KeyPair keypair = KeyTools.genKeys("512", "RSA");

    EndEntityInformation data1 = endEntityAccessSession.findUser(admin, username);
    assertNotNull(data1);
    data1.setPassword("foo123");
    endEntityManagementSession.changeUser(admin, data1, true);

    Certificate cert = signSession.createCertificate(admin, username, "foo123",
            new PublicKeyWrapper(keypair.getPublic()));
    CertificateStatus status = storeSession.getStatus(CertTools.getIssuerDN(cert),
            CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.NOT_REVOKED, status.revocationReason);
    // Revoke the certificate, put on hold
    endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, status.revocationReason);

    // Unrevoke the certificate
    endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert),
            RevokedCertInfo.NOT_REVOKED);
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.NOT_REVOKED, status.revocationReason);

    // Revoke again certificate
    endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, status.revocationReason);

    // Unrevoke the certificate, but with different code
    endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert),
            RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL);
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.NOT_REVOKED, status.revocationReason);

    // Revoke again certificate permanently
    endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert),
            RevokedCertInfo.REVOCATION_REASON_CACOMPROMISE);
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.REVOCATION_REASON_CACOMPROMISE, status.revocationReason);

    // Unrevoke the certificate, should not work
    try {
        endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(cert),
                CertTools.getIssuerDN(cert), RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL);
        assertTrue(false); // should not reach this
    } catch (AlreadyRevokedException e) {
    }
    status = storeSession.getStatus(CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert));
    assertEquals(RevokedCertInfo.REVOCATION_REASON_CACOMPROMISE, status.revocationReason);
}

From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java

/**
 * Sends a revocation request signed by RA2Admin to revoke a certificate issued by a CA RA2Admin is not authorized to. Expected: Fail
 * //from   ww w. j  a  va2s.  co m
 * @throws Exception
 */
@Test
public void test04RevocationRequest() throws Exception {

    String username = "ra1testuser";
    String fingerprintCert = null;
    try {

        // Issue a cert by CA1
        String userDN = "CN=" + username;
        createUser(username, userDN, "foo123", true, ca1.getCAId(),
                endEntityProfileSession.getEndEntityProfileId(EEP1),
                certProfileSession.getCertificateProfileId(CP1));
        KeyPair userkeys = KeyTools.genKeys("1024", "RSA");
        Certificate cert = signSession.createCertificate(ADMIN, username, "foo123",
                new PublicKeyWrapper(userkeys.getPublic()));
        assertNotNull("No certificate to revoke.", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert),
                ca1.getCACertificate(), nonce, transid, false, pAlg, null);
        assertNotNull("Generating revocation request failed.", msg);

        // Sign the revocation request with RA2 Admin
        CMPCertificate[] extraCert = getCMPCert(ra2admincert);
        PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert,
                ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed", protectedMsg);

        // Send the CMP request to RA2. Expected: Fail
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, null);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        final PKIMessage respObject;
        try {
            respObject = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull("Reading CMP response failed.", respObject);
        PKIBody body = respObject.getBody();
        assertEquals(PKIBody.TYPE_ERROR, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
        assertEquals(expectedErrMsg, errMsg);

    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused);
    }
}

From source file:org.texai.x509.X509Utils.java

/** Creates the Texai root X.509 certificate keystore on the trusted development system.  This
 * keystore also includes a jar-signing certificate.
 *//*from   w w w .  j  a v  a2 s.c  om*/
protected static synchronized void createTexaiRootKeyStore() {
    //Preconditions
    assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy();

    if (!isTrustedDevelopmentSystem()) {
        return;
    }
    final char[] keyStorePassword = getRootKeyStorePassword();
    assert keyStorePassword != null;
    final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
    final File serverKeyStoreFile = new File(filePath);
    if (serverKeyStoreFile.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating Texai root key pair");
        final KeyPair rootKeyPair = generateRSAKeyPair3072();
        LOGGER.info("creating Texai root X.509 certificate");
        final X509Certificate rootX509Certificate = generateRootX509Certificate(rootKeyPair);
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        final StringBuilder stringBuilder = new StringBuilder();
        for (final byte b : rootX509Certificate.getEncoded()) {
            stringBuilder.append(Byte.toString(b));
            stringBuilder.append(", ");
        }
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        LOGGER.info("\nroot certificate bytes...\n" + stringBuilder.toString());
        LOGGER.info("creating Texai root X.509 certificate keystore");
        final KeyStore rootKeyStore = X509Utils.findOrCreateJceksKeyStore(filePath, keyStorePassword);
        rootKeyStore.setKeyEntry(ROOT_ALIAS, rootKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { rootX509Certificate });

        // create and store the jar-signer certificate
        LOGGER.info("creating jar-signer key pair");
        final KeyPair jarSignerKeyPair = generateRSAKeyPair2048();
        LOGGER.info("creating jar-signer X.509 certificate");
        final UUID jarSignerUUID = UUID.randomUUID();
        LOGGER.info("jar-signer UUID: " + jarSignerUUID);
        final X509Certificate jarSignerX509Certificate = generateX509Certificate(jarSignerKeyPair.getPublic(),
                rootKeyPair.getPrivate(), rootX509Certificate, jarSignerUUID, "RootCertificate"); // domainComponent
        LOGGER.info("jar-signer certificate:\n" + jarSignerX509Certificate);
        rootKeyStore.setKeyEntry(JAR_SIGNER_ALIAS, jarSignerKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { jarSignerX509Certificate, rootX509Certificate });
        rootKeyStore.store(new FileOutputStream(filePath), keyStorePassword);

        //Postconditions
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);
        assert privateKey != null;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException
            | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java

/**
 * Prepare activation with given parameters
 *
 * @param activationIdShort              Short activation ID
 * @param activationNonceBase64          Activation nonce encoded as Base64
 * @param clientEphemeralPublicKeyBase64 Client ephemeral public key encoded as Base64
 * @param cDevicePublicKeyBase64         Encrypted device public key encoded as Base64
 * @param activationName                 Activation name
 * @param extras                         Extra parameter
 * @param applicationKey                 Application key
 * @param applicationSignature           Application signature
 * @param keyConversionUtilities         Utility class for key conversion
 * @return Prepared activation information
 * @throws GenericServiceException      In case invalid data is provided
 * @throws InvalidKeySpecException      If invalid key was provided
 * @throws InvalidKeyException          If invalid key was provided
 * @throws UnsupportedEncodingException If UTF-8 is not supported on the system
 *///w  w  w .j  a v  a  2 s .  c  om
public PrepareActivationResponse prepareActivation(String activationIdShort, String activationNonceBase64,
        String clientEphemeralPublicKeyBase64, String cDevicePublicKeyBase64, String activationName,
        String extras, String applicationKey, String applicationSignature,
        CryptoProviderUtil keyConversionUtilities) throws GenericServiceException, InvalidKeySpecException,
        InvalidKeyException, UnsupportedEncodingException {

    // Get current timestamp
    Date timestamp = new Date();

    ApplicationVersionEntity applicationVersion = applicationVersionRepository
            .findByApplicationKey(applicationKey);
    // if there is no such application, exit
    if (applicationVersion == null || applicationVersion.getSupported() == false) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    ApplicationEntity application = applicationVersion.getApplication();
    // if there is no such application, exit
    if (application == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Fetch the current activation by short activation ID
    Set<io.getlime.security.powerauth.app.server.repository.model.ActivationStatus> states = ImmutableSet
            .of(io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED);
    ActivationRecordEntity activation = powerAuthRepository
            .findFirstByApplicationIdAndActivationIdShortAndActivationStatusInAndTimestampActivationExpireAfter(
                    application.getId(), activationIdShort, states, timestamp);

    // Make sure to deactivate the activation if it is expired
    if (activation != null) {
        deactivatePendingActivation(timestamp, activation);
    }

    // if there is no such activation or application does not match the activation application, exit
    if (activation == null
            || !io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED
                    .equals(activation.getActivationStatus())
            || activation.getApplication().getId() != application.getId()) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Get master private key
    String masterPrivateKeyBase64 = activation.getMasterKeyPair().getMasterKeyPrivateBase64();
    byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterPrivateKeyBase64);
    PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes);

    // Get client ephemeral public key
    PublicKey clientEphemeralPublicKey = null;
    if (clientEphemeralPublicKeyBase64 != null) { // additional encryption is used
        byte[] clientEphemeralPublicKeyBytes = BaseEncoding.base64().decode(clientEphemeralPublicKeyBase64);
        clientEphemeralPublicKey = keyConversionUtilities
                .convertBytesToPublicKey(clientEphemeralPublicKeyBytes);
    }

    // Decrypt the device public key
    byte[] C_devicePublicKey = BaseEncoding.base64().decode(cDevicePublicKeyBase64);
    byte[] activationNonce = BaseEncoding.base64().decode(activationNonceBase64);
    PublicKey devicePublicKey = powerAuthServerActivation.decryptDevicePublicKey(C_devicePublicKey,
            activationIdShort, masterPrivateKey, clientEphemeralPublicKey, activation.getActivationOTP(),
            activationNonce);

    if (devicePublicKey == null) { // invalid key was sent, return error
        activation.setActivationStatus(
                io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.REMOVED);
        powerAuthRepository.save(activation);
        callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
                activation.getActivationId());
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_NOT_FOUND);
    }

    byte[] applicationSignatureBytes = BaseEncoding.base64().decode(applicationSignature);

    if (!powerAuthServerActivation.validateApplicationSignature(activationIdShort, activationNonce,
            C_devicePublicKey, BaseEncoding.base64().decode(applicationKey),
            BaseEncoding.base64().decode(applicationVersion.getApplicationSecret()),
            applicationSignatureBytes)) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Update and persist the activation record
    activation.setActivationStatus(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED);
    activation.setDevicePublicKeyBase64(
            BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(devicePublicKey)));
    activation.setActivationName(activationName);
    activation.setExtras(extras);
    powerAuthRepository.save(activation);
    callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
            activation.getActivationId());

    // Generate response data
    byte[] activationNonceServer = powerAuthServerActivation.generateActivationNonce();
    String serverPublicKeyBase64 = activation.getServerPublicKeyBase64();
    PublicKey serverPublicKey = keyConversionUtilities
            .convertBytesToPublicKey(BaseEncoding.base64().decode(serverPublicKeyBase64));
    KeyPair ephemeralKeyPair = new KeyGenerator().generateKeyPair();
    PrivateKey ephemeralPrivateKey = ephemeralKeyPair.getPrivate();
    PublicKey ephemeralPublicKey = ephemeralKeyPair.getPublic();
    byte[] ephemeralPublicKeyBytes = keyConversionUtilities.convertPublicKeyToBytes(ephemeralPublicKey);
    String activationOtp = activation.getActivationOTP();

    // Encrypt the public key
    byte[] C_serverPublicKey = powerAuthServerActivation.encryptServerPublicKey(serverPublicKey,
            devicePublicKey, ephemeralPrivateKey, activationOtp, activationIdShort, activationNonceServer);

    // Get encrypted public key signature
    byte[] C_serverPubKeySignature = powerAuthServerActivation
            .computeServerDataSignature(activation.getActivationId(), C_serverPublicKey, masterPrivateKey);
    if (C_serverPubKeySignature == null) { // in case there is a technical error with signing and null is returned, return random bytes
        C_serverPubKeySignature = new KeyGenerator().generateRandomBytes(71);
    }

    // Compute the response
    PrepareActivationResponse response = new PrepareActivationResponse();
    response.setActivationId(activation.getActivationId());
    response.setActivationNonce(BaseEncoding.base64().encode(activationNonceServer));
    response.setEncryptedServerPublicKey(BaseEncoding.base64().encode(C_serverPublicKey));
    response.setEncryptedServerPublicKeySignature(BaseEncoding.base64().encode(C_serverPubKeySignature));
    response.setEphemeralPublicKey(BaseEncoding.base64().encode(ephemeralPublicKeyBytes));

    return response;
}