2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.netconf.ssh.authentication;
11 import java.security.NoSuchAlgorithmException;
12 import org.apache.commons.io.FileUtils;
13 import org.bouncycastle.openssl.PEMWriter;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
18 import java.io.IOException;
19 import java.io.StringWriter;
20 import java.security.Key;
21 import java.security.KeyPair;
22 import java.security.KeyPairGenerator;
23 import java.security.SecureRandom;
25 public class PEMGenerator {
26 private static final Logger logger = LoggerFactory.getLogger(PEMGenerator.class);
27 private static final int KEY_SIZE = 4096;
29 public static String generateTo(File privateFile) throws IOException, NoSuchAlgorithmException {
30 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
31 SecureRandom sr = new SecureRandom();
32 keyGen.initialize(KEY_SIZE, sr);
33 KeyPair keypair = keyGen.generateKeyPair();
34 logger.info("Generating private key to {}", privateFile.getAbsolutePath());
35 String privatePEM = toString(keypair.getPrivate());
36 FileUtils.write(privateFile, privatePEM);
40 private static String toString(Key key) throws IOException {
41 try (StringWriter writer = new StringWriter()) {
42 try (PEMWriter pemWriter = new PEMWriter(writer)) {
43 pemWriter.writeObject(key);
45 return writer.toString();