Crypto.java

package jasper.util;

import org.apache.sshd.common.config.keys.writer.openssh.OpenSSHKeyPairResourceWriter;
import org.apache.sshd.common.util.security.SecurityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PublicKey;

public class Crypto {

	/**
	 * Generate an SSH key pair.
	 * @param type "ed25519", "ecdsa" or "rsa"
	 * @param size bits for "ecdsa" (256, 384 or 521, default 256) and "rsa" (default 4096). Ignored for "ed25519".
	 */
	public static KeyPair keyPair(String type, Integer size) throws GeneralSecurityException {
		var kpg = switch (type) {
			case "ed25519" -> SecurityUtils.getKeyPairGenerator(SecurityUtils.EDDSA);
			case "ecdsa" -> SecurityUtils.getKeyPairGenerator("EC");
			case "rsa" -> SecurityUtils.getKeyPairGenerator("RSA");
			default -> throw new IllegalArgumentException("Unsupported key type " + type);
		};
		kpg.initialize(switch (type) {
			case "ecdsa" -> size == null ? 256 : size;
			case "rsa" -> size == null ? 4096 : size;
			default -> 256;
		});
		return kpg.generateKeyPair();
	}

	public static byte[] writeSshPrivateKey(KeyPair keyPair) throws IOException, GeneralSecurityException {
		var out = new ByteArrayOutputStream();
		OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(keyPair, null, null, out);
		return out.toByteArray();
	}

	public static byte[] writeSshPublicKey(PublicKey publicKey, String comment) throws IOException, GeneralSecurityException {
		var out = new ByteArrayOutputStream();
		OpenSSHKeyPairResourceWriter.INSTANCE.writePublicKey(publicKey, comment, out);
		return out.toString().trim().getBytes();
	}
}