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 org.apache.commons.io.FileUtils;
12 import org.bouncycastle.openssl.PEMWriter;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
17 import java.io.IOException;
18 import java.io.StringWriter;
19 import java.security.Key;
20 import java.security.KeyPair;
21 import java.security.KeyPairGenerator;
22 import java.security.SecureRandom;
24 public class PEMGenerator {
25 private static final Logger logger = LoggerFactory.getLogger(PEMGenerator.class);
26 private static final int KEY_SIZE = 4096;
28 public static String generateTo(File privateFile) throws Exception {
29 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
30 SecureRandom sr = new SecureRandom();
31 keyGen.initialize(KEY_SIZE, sr);
32 KeyPair keypair = keyGen.generateKeyPair();
33 logger.info("Generating private key to {}", privateFile.getAbsolutePath());
34 String privatePEM = toString(keypair.getPrivate());
35 FileUtils.write(privateFile, privatePEM);
39 private static String toString(Key key) throws IOException {
40 try (StringWriter writer = new StringWriter()) {
41 try (PEMWriter pemWriter = new PEMWriter(writer)) {
42 pemWriter.writeObject(key);
44 return writer.toString();