/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.megatim.module.encryption.cipher.asymetric; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; /** * * @author STEPHANIE */ public class GenerateKeys { private KeyPairGenerator keyGen; private KeyPair pair; private PrivateKey privateKey; private PublicKey publicKey; public GenerateKeys(int keylength) throws NoSuchAlgorithmException, NoSuchProviderException { this.keyGen = KeyPairGenerator.getInstance("RSA"); this.keyGen.initialize(keylength); } public void createKeys() { this.pair = this.keyGen.generateKeyPair(); this.privateKey = pair.getPrivate(); this.publicKey = pair.getPublic(); } public PrivateKey getPrivateKey() { return this.privateKey; } public PublicKey getPublicKey() { return this.publicKey; } public void writeToFile(String path, byte[] key) throws IOException { File f = new File(path); f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); fos.write(key); fos.flush(); fos.close(); } public static void generateKeys(int keyLength,String pathToPrivateKey, String pathToPublicKey) { try { GenerateKeys gk; gk = new GenerateKeys(keyLength); gk.createKeys(); gk.writeToFile(pathToPublicKey, gk.getPublicKey().getEncoded()); gk.writeToFile(pathToPrivateKey, gk.getPrivateKey().getEncoded()); } catch (NoSuchAlgorithmException | NoSuchProviderException | IOException e) { System.err.println(e.getMessage()); } } }