Resolve Bug:623 : Generate private key using bouncycastle.
[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 org.apache.commons.io.FileUtils;
12 import org.bouncycastle.openssl.PEMWriter;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 import java.io.File;
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;
23
24 public class PEMGenerator {
25     private static final Logger logger = LoggerFactory.getLogger(PEMGenerator.class);
26     private static final int KEY_SIZE = 4096;
27
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);
36         return privatePEM;
37     }
38
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);
43             }
44             return writer.toString();
45         }
46     }
47 }