package de.ivu.elect.encrypt;

import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class Base64KeyConverter {

  private final KeyConverterConfig keyGeneratorConfig;

  public Base64KeyConverter(KeyConverterConfig keyGeneratorConfig) {
    this.keyGeneratorConfig = keyGeneratorConfig;
  }

  public String convertToBase64(Key key) {
    return Base64.getEncoder().encodeToString(key.getEncoded());
  }

  public PrivateKey convertBase64ToPrivateKey(String privateKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(keyGeneratorConfig.getAlgorithm());
    return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBase64)));
  }

  public PublicKey convertBase64ToPublicKey(String publicKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(keyGeneratorConfig.getAlgorithm());
    return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBase64)));
  }

}
