package com.atlassian.bitbucket.internal.mirroring.ssh.encoding;

import org.bouncycastle.openssl.jcajce.JcaPEMWriter;

import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

/**
 * Encodes/decodes a private key to/from a PEM file
 */
public class DefaultPrivateKeyPemHelper implements PrivateKeyPemHelper {

    @Override
    public void write(@Nonnull PrivateKey privateKey, @Nonnull File keyFile) {
        try (JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(new FileOutputStream(keyFile), StandardCharsets.US_ASCII))) {
            pemWriter.writeObject(privateKey);
        } catch (Exception e) {
            throw new KeyCodecException(e);
        }
    }
}
