BUG-624 make netconf tcp address optional in config.ini with default value set to...
[controller.git] / opendaylight / netconf / netconf-ssh / src / main / java / org / opendaylight / controller / netconf / ssh / authentication / PEMGenerator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.ssh.authentication;
10
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;
16
17 import java.io.File;
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;
24
25 public class PEMGenerator {
26     private static final Logger logger = LoggerFactory.getLogger(PEMGenerator.class);
27     private static final int KEY_SIZE = 4096;
28
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);
37         return privatePEM;
38     }
39
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);
44             }
45             return writer.toString();
46         }
47     }
48 }