2 ConnectBot: simple, powerful, open-source SSH client for Android
3 Copyright (C) 2007-2008 Kenny Root, Jeffrey Sharkey
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package org.connectbot.util;
21 import java.io.IOException;
22 import java.math.BigInteger;
23 import java.security.AlgorithmParameters;
24 import java.security.InvalidAlgorithmParameterException;
25 import java.security.InvalidKeyException;
26 import java.security.Key;
27 import java.security.KeyFactory;
28 import java.security.KeyPair;
29 import java.security.MessageDigest;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.PrivateKey;
32 import java.security.PublicKey;
33 import java.security.SecureRandom;
34 import java.security.interfaces.DSAParams;
35 import java.security.interfaces.DSAPrivateKey;
36 import java.security.interfaces.DSAPublicKey;
37 import java.security.interfaces.RSAPrivateCrtKey;
38 import java.security.interfaces.RSAPrivateKey;
39 import java.security.interfaces.RSAPublicKey;
40 import java.security.spec.DSAPublicKeySpec;
41 import java.security.spec.InvalidKeySpecException;
42 import java.security.spec.InvalidParameterSpecException;
43 import java.security.spec.KeySpec;
44 import java.security.spec.PKCS8EncodedKeySpec;
45 import java.security.spec.RSAPublicKeySpec;
46 import java.security.spec.X509EncodedKeySpec;
47 import java.util.Arrays;
49 import javax.crypto.BadPaddingException;
50 import javax.crypto.Cipher;
51 import javax.crypto.EncryptedPrivateKeyInfo;
52 import javax.crypto.IllegalBlockSizeException;
53 import javax.crypto.NoSuchPaddingException;
54 import javax.crypto.SecretKeyFactory;
55 import javax.crypto.spec.PBEKeySpec;
56 import javax.crypto.spec.PBEParameterSpec;
57 import javax.crypto.spec.SecretKeySpec;
59 import android.util.Log;
61 import com.trilead.ssh2.crypto.Base64;
62 import com.trilead.ssh2.signature.DSASHA1Verify;
63 import com.trilead.ssh2.signature.RSASHA1Verify;
65 public class PubkeyUtils {
66 public static final String PKCS8_START = "-----BEGIN PRIVATE KEY-----";
67 public static final String PKCS8_END = "-----END PRIVATE KEY-----";
69 // Size in bytes of salt to use.
70 private static final int SALT_SIZE = 8;
72 // Number of iterations for password hashing. PKCS#5 recommends 1000
73 private static final int ITERATIONS = 1000;
75 public static String formatKey(Key key){
76 String algo = key.getAlgorithm();
77 String fmt = key.getFormat();
78 byte[] encoded = key.getEncoded();
79 return "Key[algorithm=" + algo + ", format=" + fmt +
80 ", bytes=" + encoded.length + "]";
83 public static String describeKey(Key key, boolean encrypted) {
85 if (key instanceof RSAPublicKey) {
86 int bits = ((RSAPublicKey)key).getModulus().bitLength();
87 desc = "RSA " + String.valueOf(bits) + "-bit";
88 } else if (key instanceof DSAPublicKey) {
89 desc = "DSA 1024-bit";
91 desc = "Unknown Key Type";
95 desc += " (encrypted)";
100 public static byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
101 return MessageDigest.getInstance("SHA-256").digest(data);
104 public static byte[] cipher(int mode, byte[] data, byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
105 SecretKeySpec secretKeySpec = new SecretKeySpec(sha256(secret), "AES");
106 Cipher c = Cipher.getInstance("AES");
107 c.init(mode, secretKeySpec);
108 return c.doFinal(data);
111 public static byte[] encrypt(byte[] cleartext, String secret) throws Exception {
112 byte[] salt = new byte[SALT_SIZE];
114 byte[] ciphertext = Encryptor.encrypt(salt, ITERATIONS, secret, cleartext);
116 byte[] complete = new byte[salt.length + ciphertext.length];
118 System.arraycopy(salt, 0, complete, 0, salt.length);
119 System.arraycopy(ciphertext, 0, complete, salt.length, ciphertext.length);
121 Arrays.fill(salt, (byte) 0x00);
122 Arrays.fill(ciphertext, (byte) 0x00);
127 public static byte[] decrypt(byte[] complete, String secret) throws Exception {
129 byte[] salt = new byte[SALT_SIZE];
130 byte[] ciphertext = new byte[complete.length - salt.length];
132 System.arraycopy(complete, 0, salt, 0, salt.length);
133 System.arraycopy(complete, salt.length, ciphertext, 0, ciphertext.length);
135 return Encryptor.decrypt(salt, ITERATIONS, secret, ciphertext);
136 } catch (Exception e) {
137 Log.d("decrypt", "Could not decrypt with new method", e);
138 // We might be using the old encryption method.
139 return cipher(Cipher.DECRYPT_MODE, complete, secret.getBytes());
143 public static byte[] getEncodedPublic(PublicKey pk) {
144 return new X509EncodedKeySpec(pk.getEncoded()).getEncoded();
147 public static byte[] getEncodedPrivate(PrivateKey pk) {
148 return new PKCS8EncodedKeySpec(pk.getEncoded()).getEncoded();
151 public static byte[] getEncodedPrivate(PrivateKey pk, String secret) throws Exception {
152 if (secret.length() > 0)
153 return encrypt(getEncodedPrivate(pk), secret);
155 return getEncodedPrivate(pk);
158 public static PrivateKey decodePrivate(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
159 PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
160 KeyFactory kf = KeyFactory.getInstance(keyType);
161 return kf.generatePrivate(privKeySpec);
164 public static PrivateKey decodePrivate(byte[] encoded, String keyType, String secret) throws Exception {
165 if (secret != null && secret.length() > 0)
166 return decodePrivate(decrypt(encoded, secret), keyType);
168 return decodePrivate(encoded, keyType);
171 public static PublicKey decodePublic(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
172 X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
173 KeyFactory kf = KeyFactory.getInstance(keyType);
174 return kf.generatePublic(pubKeySpec);
177 public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException, InvalidKeySpecException {
178 KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
185 kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_RSA);
186 priv = kf.generatePrivate(privKeySpec);
188 pubKeySpec = new RSAPublicKeySpec(((RSAPrivateCrtKey) priv)
189 .getModulus(), ((RSAPrivateCrtKey) priv)
190 .getPublicExponent());
192 pub = kf.generatePublic(pubKeySpec);
193 } catch (ClassCastException e) {
194 kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_DSA);
195 priv = kf.generatePrivate(privKeySpec);
197 DSAParams params = ((DSAPrivateKey) priv).getParams();
199 // Calculate public key Y
200 BigInteger y = params.getG().modPow(((DSAPrivateKey) priv).getX(),
203 pubKeySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(),
206 pub = kf.generatePublic(pubKeySpec);
209 return new KeyPair(pub, priv);
213 * Trilead compatibility methods
216 public static Object convertToTrilead(PublicKey pk) {
217 if (pk instanceof RSAPublicKey) {
218 return new com.trilead.ssh2.signature.RSAPublicKey(
219 ((RSAPublicKey) pk).getPublicExponent(),
220 ((RSAPublicKey) pk).getModulus());
221 } else if (pk instanceof DSAPublicKey) {
222 DSAParams dp = ((DSAPublicKey) pk).getParams();
223 return new com.trilead.ssh2.signature.DSAPublicKey(
224 dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pk).getY());
227 throw new IllegalArgumentException("PublicKey is not RSA or DSA format");
230 public static Object convertToTrilead(PrivateKey priv, PublicKey pub) {
231 if (priv instanceof RSAPrivateKey) {
232 return new com.trilead.ssh2.signature.RSAPrivateKey(
233 ((RSAPrivateKey) priv).getPrivateExponent(),
234 ((RSAPublicKey) pub).getPublicExponent(),
235 ((RSAPrivateKey) priv).getModulus());
236 } else if (priv instanceof DSAPrivateKey) {
237 DSAParams dp = ((DSAPrivateKey) priv).getParams();
238 return new com.trilead.ssh2.signature.DSAPrivateKey(
239 dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pub).getY(),
240 ((DSAPrivateKey) priv).getX());
243 throw new IllegalArgumentException("Key is not RSA or DSA format");
247 * OpenSSH compatibility methods
250 public static String convertToOpenSSHFormat(PublicKey pk, String origNickname) throws IOException, InvalidKeyException {
251 String nickname = origNickname;
252 if (nickname == null)
253 nickname = "connectbot@android";
255 if (pk instanceof RSAPublicKey) {
256 String data = "ssh-rsa ";
257 data += String.valueOf(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey(
258 (com.trilead.ssh2.signature.RSAPublicKey)convertToTrilead(pk))));
259 return data + " " + nickname;
260 } else if (pk instanceof DSAPublicKey) {
261 String data = "ssh-dss ";
262 data += String.valueOf(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey(
263 (com.trilead.ssh2.signature.DSAPublicKey)convertToTrilead(pk))));
264 return data + " " + nickname;
267 throw new InvalidKeyException("Unknown key type");
271 * OpenSSH compatibility methods
276 * @return OpenSSH-encoded pubkey
278 public static byte[] extractOpenSSHPublic(Object trileadKey) {
280 if (trileadKey instanceof com.trilead.ssh2.signature.RSAPrivateKey)
281 return RSASHA1Verify.encodeSSHRSAPublicKey(
282 ((com.trilead.ssh2.signature.RSAPrivateKey) trileadKey).getPublicKey());
283 else if (trileadKey instanceof com.trilead.ssh2.signature.DSAPrivateKey)
284 return DSASHA1Verify.encodeSSHDSAPublicKey(
285 ((com.trilead.ssh2.signature.DSAPrivateKey) trileadKey).getPublicKey());
288 } catch (IOException e) {
293 public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
294 StringBuilder sb = new StringBuilder();
296 byte[] data = key.getEncoded();
298 sb.append(PKCS8_START);
301 if (secret != null) {
302 byte[] salt = new byte[8];
303 SecureRandom random = new SecureRandom();
304 random.nextBytes(salt);
306 PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
307 AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
309 params.init(defParams);
311 PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
313 SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
314 Cipher cipher = Cipher.getInstance(key.getAlgorithm());
315 cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
317 byte[] wrappedKey = cipher.wrap(key);
319 EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
321 data = pinfo.getEncoded();
323 sb.append("Proc-Type: 4,ENCRYPTED\n");
324 sb.append("DEK-Info: DES-EDE3-CBC,");
325 sb.append(encodeHex(salt));
330 sb.append(Base64.encode(data));
331 for (i += 63; i < sb.length(); i += 64) {
336 sb.append(PKCS8_END);
339 return sb.toString();
342 final static private char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6',
343 '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
344 private static String encodeHex(byte[] bytes) {
345 char[] hex = new char[bytes.length * 2];
348 for (byte b : bytes) {
349 hex[i++] = hexDigit[(b >> 4) & 0x0f];
350 hex[i++] = hexDigit[b & 0x0f];
353 return new String(hex);