// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.athenz.instanceproviderservice;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author bjorncs
 */
public class AutoGeneratedKeyProvider implements KeyProvider {

    private final KeyPair keyPair;

    public AutoGeneratedKeyProvider() {
        try {
            KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
            rsa.initialize(2048);
            keyPair = rsa.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PrivateKey getPrivateKey(int version) {
        return keyPair.getPrivate();
    }

    @Override
    public PublicKey getPublicKey(int version) {
        return keyPair.getPublic();
    }

    public KeyPair getKeyPair() {
        return keyPair;
    }
}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.athenz.instanceproviderservice;

import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author bjorncs
 */
public class AutoGeneratedKeyProvider implements KeyProvider {

    private final KeyPair keyPair;

    public AutoGeneratedKeyProvider() {
        keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
    }

    @Override
    public PrivateKey getPrivateKey(int version) {
        return keyPair.getPrivate();
    }

    @Override
    public PublicKey getPublicKey(int version) {
        return keyPair.getPublic();
    }

    public KeyPair getKeyPair() {
        return keyPair;
    }
}

Use KeyUtils