e544195fd8045c32bcc8ffb6d008e45b9fbc6584
[netconf.git] / netconf / callhome-protocol / src / main / java / org / opendaylight / netconf / callhome / protocol / AuthorizedKeysDecoder.java
1 /*
2  * Copyright (c) 2016 Brocade Communication Systems 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 package org.opendaylight.netconf.callhome.protocol;
9
10 import java.io.ByteArrayOutputStream;
11 import java.io.DataOutputStream;
12 import java.io.IOException;
13 import java.math.BigInteger;
14 import java.security.GeneralSecurityException;
15 import java.security.KeyFactory;
16 import java.security.PublicKey;
17 import java.security.interfaces.DSAParams;
18 import java.security.interfaces.DSAPublicKey;
19 import java.security.interfaces.RSAPublicKey;
20 import java.security.spec.DSAPublicKeySpec;
21 import java.security.spec.ECPoint;
22 import java.security.spec.ECPublicKeySpec;
23 import java.security.spec.RSAPublicKeySpec;
24 import java.util.Arrays;
25 import java.util.Base64;
26 import java.util.HashMap;
27 import java.util.Map;
28 import org.apache.sshd.common.util.security.SecurityUtils;
29 import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
30 import org.bouncycastle.jce.ECNamedCurveTable;
31 import org.bouncycastle.jce.ECPointUtil;
32 import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
33 import org.bouncycastle.jce.spec.ECNamedCurveSpec;
34
35 /**
36  * FIXME: This should be probably located at AAA library.
37  */
38 public class AuthorizedKeysDecoder {
39
40     private static final String KEY_FACTORY_TYPE_RSA = "RSA";
41     private static final String KEY_FACTORY_TYPE_DSA = "DSA";
42     private static final String KEY_FACTORY_TYPE_ECDSA = "EC";
43
44     private static final Map<String, String> ECDSA_CURVES = new HashMap<>();
45
46     static {
47         ECDSA_CURVES.put("nistp256", "secp256r1");
48         ECDSA_CURVES.put("nistp384", "secp384r1");
49         ECDSA_CURVES.put("nistp512", "secp512r1");
50     }
51
52     private static final String ECDSA_SUPPORTED_CURVE_NAME = "nistp256";
53     private static final String ECDSA_SUPPORTED_CURVE_NAME_SPEC = ECDSA_CURVES.get(ECDSA_SUPPORTED_CURVE_NAME);
54
55     private static final String KEY_TYPE_RSA = "ssh-rsa";
56     private static final String KEY_TYPE_DSA = "ssh-dss";
57     private static final String KEY_TYPE_ECDSA = "ecdsa-sha2-" + ECDSA_SUPPORTED_CURVE_NAME;
58
59     private byte[] bytes = new byte[0];
60     private int pos = 0;
61
62     public PublicKey decodePublicKey(final String keyLine) throws GeneralSecurityException {
63
64         // look for the Base64 encoded part of the line to decode
65         // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
66         bytes = Base64.getDecoder().decode(keyLine.getBytes());
67         if (bytes.length == 0) {
68             throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
69         }
70
71         pos = 0;
72
73         String type = decodeType();
74         if (type.equals(KEY_TYPE_RSA)) {
75             return decodeAsRSA();
76         }
77
78         if (type.equals(KEY_TYPE_DSA)) {
79             return decodeAsDSA();
80         }
81
82         if (type.equals(KEY_TYPE_ECDSA)) {
83             return decodeAsEcDSA();
84         }
85
86         throw new IllegalArgumentException("Unknown decode key type " + type + " in " + keyLine);
87     }
88
89     private PublicKey decodeAsEcDSA() throws GeneralSecurityException {
90         KeyFactory ecdsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_ECDSA);
91
92         ECNamedCurveParameterSpec spec256r1 = ECNamedCurveTable.getParameterSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC);
93         ECNamedCurveSpec params256r1 = new ECNamedCurveSpec(
94             ECDSA_SUPPORTED_CURVE_NAME_SPEC, spec256r1.getCurve(), spec256r1.getG(), spec256r1.getN());
95         // copy last 65 bytes from ssh key.
96         ECPoint point = ECPointUtil.decodePoint(params256r1.getCurve(), Arrays.copyOfRange(bytes, 39, bytes.length));
97         ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params256r1);
98
99         return ecdsaFactory.generatePublic(pubKeySpec);
100     }
101
102     private PublicKey decodeAsDSA() throws GeneralSecurityException {
103         KeyFactory dsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_DSA);
104         BigInteger prime = decodeBigInt();
105         BigInteger subPrime = decodeBigInt();
106         BigInteger base = decodeBigInt();
107         BigInteger publicKey = decodeBigInt();
108         DSAPublicKeySpec spec = new DSAPublicKeySpec(publicKey, prime, subPrime, base);
109
110         return dsaFactory.generatePublic(spec);
111     }
112
113     private PublicKey decodeAsRSA() throws GeneralSecurityException {
114         KeyFactory rsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_RSA);
115         BigInteger exponent = decodeBigInt();
116         BigInteger modulus = decodeBigInt();
117         RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
118
119         return rsaFactory.generatePublic(spec);
120     }
121
122     private String decodeType() {
123         int len = decodeInt();
124         String type = new String(bytes, pos, len);
125         pos += len;
126         return type;
127     }
128
129     private int decodeInt() {
130         return (bytes[pos++] & 0xFF) << 24 | (bytes[pos++] & 0xFF) << 16
131                 | (bytes[pos++] & 0xFF) << 8 | bytes[pos++] & 0xFF;
132     }
133
134     private BigInteger decodeBigInt() {
135         int len = decodeInt();
136         byte[] bigIntBytes = new byte[len];
137         System.arraycopy(bytes, pos, bigIntBytes, 0, len);
138         pos += len;
139         return new BigInteger(bigIntBytes);
140     }
141
142     public static String encodePublicKey(final PublicKey publicKey) throws IOException {
143         String publicKeyEncoded;
144         ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
145         if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) {
146             RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
147             DataOutputStream dout = new DataOutputStream(byteOs);
148             dout.writeInt(KEY_TYPE_RSA.getBytes().length);
149             dout.write(KEY_TYPE_RSA.getBytes());
150             dout.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
151             dout.write(rsaPublicKey.getPublicExponent().toByteArray());
152             dout.writeInt(rsaPublicKey.getModulus().toByteArray().length);
153             dout.write(rsaPublicKey.getModulus().toByteArray());
154         } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA)) {
155             DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
156             DSAParams dsaParams = dsaPublicKey.getParams();
157             DataOutputStream dout = new DataOutputStream(byteOs);
158             dout.writeInt(KEY_TYPE_DSA.getBytes().length);
159             dout.write(KEY_TYPE_DSA.getBytes());
160             dout.writeInt(dsaParams.getP().toByteArray().length);
161             dout.write(dsaParams.getP().toByteArray());
162             dout.writeInt(dsaParams.getQ().toByteArray().length);
163             dout.write(dsaParams.getQ().toByteArray());
164             dout.writeInt(dsaParams.getG().toByteArray().length);
165             dout.write(dsaParams.getG().toByteArray());
166             dout.writeInt(dsaPublicKey.getY().toByteArray().length);
167             dout.write(dsaPublicKey.getY().toByteArray());
168         } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA)) {
169             BCECPublicKey ecPublicKey = (BCECPublicKey) publicKey;
170             DataOutputStream dout = new DataOutputStream(byteOs);
171             dout.writeInt(KEY_TYPE_ECDSA.getBytes().length);
172             dout.write(KEY_TYPE_ECDSA.getBytes());
173             dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length);
174             dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes());
175
176             byte[] coordX = ecPublicKey.getQ().getAffineXCoord().getEncoded();
177             byte[] coordY = ecPublicKey.getQ().getAffineYCoord().getEncoded();
178             dout.writeInt(coordX.length + coordY.length + 1);
179             dout.writeByte(0x04);
180             dout.write(coordX);
181             dout.write(coordY);
182         } else {
183             throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
184         }
185         publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray()));
186         return publicKeyEncoded;
187     }
188 }