comparison src/ch/ethz/ssh2/KnownHosts.java @ 273:91a31873c42a ganymed

start conversion from trilead to ganymed
author Carl Byington <carl@five-ten-sg.com>
date Fri, 18 Jul 2014 11:21:46 -0700
parents
children d7e088fa2123
comparison
equal deleted inserted replaced
272:ce2f4e397703 273:91a31873c42a
1 /*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5
6 package ch.ethz.ssh2;
7
8 import java.io.BufferedReader;
9 import java.io.CharArrayReader;
10 import java.io.CharArrayWriter;
11 import java.io.File;
12 import java.io.FileReader;
13 import java.io.IOException;
14 import java.io.RandomAccessFile;
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.security.DigestException;
18 import java.security.SecureRandom;
19 import java.util.ArrayList;
20 import java.util.LinkedList;
21 import java.util.List;
22
23 import ch.ethz.ssh2.crypto.Base64;
24 import ch.ethz.ssh2.crypto.digest.Digest;
25 import ch.ethz.ssh2.crypto.digest.HMAC;
26 import ch.ethz.ssh2.crypto.digest.MD5;
27 import ch.ethz.ssh2.crypto.digest.SHA1;
28 import ch.ethz.ssh2.signature.DSAPublicKey;
29 import ch.ethz.ssh2.signature.DSASHA1Verify;
30 import ch.ethz.ssh2.signature.RSAPublicKey;
31 import ch.ethz.ssh2.signature.RSASHA1Verify;
32 import ch.ethz.ssh2.util.StringEncoder;
33
34 /**
35 * The <code>KnownHosts</code> class is a handy tool to verify received server hostkeys
36 * based on the information in <code>known_hosts</code> files (the ones used by OpenSSH).
37 * <p/>
38 * It offers basically an in-memory database for known_hosts entries, as well as some
39 * helper functions. Entries from a <code>known_hosts</code> file can be loaded at construction time.
40 * It is also possible to add more keys later (e.g., one can parse different
41 * <code>known_hosts<code> files).
42 * <p/>
43 * It is a thread safe implementation, therefore, you need only to instantiate one
44 * <code>KnownHosts</code> for your whole application.
45 *
46 * @author Christian Plattner
47 * @version $Id: KnownHosts.java 152 2014-04-28 11:02:23Z dkocher@sudo.ch $
48 */
49
50 public class KnownHosts {
51 public static final int HOSTKEY_IS_OK = 0;
52 public static final int HOSTKEY_IS_NEW = 1;
53 public static final int HOSTKEY_HAS_CHANGED = 2;
54
55 private class KnownHostsEntry {
56 String[] patterns;
57 Object key;
58
59 KnownHostsEntry(String[] patterns, Object key) {
60 this.patterns = patterns;
61 this.key = key;
62 }
63 }
64
65 private final LinkedList<KnownHostsEntry> publicKeys = new LinkedList<KnownHosts.KnownHostsEntry>();
66
67 public KnownHosts() {
68 }
69
70 public KnownHosts(char[] knownHostsData) throws IOException {
71 initialize(knownHostsData);
72 }
73
74 public KnownHosts(String knownHosts) throws IOException {
75 initialize(new File(knownHosts));
76 }
77
78 public KnownHosts(File knownHosts) throws IOException {
79 initialize(knownHosts);
80 }
81
82 /**
83 * Adds a single public key entry to the database. Note: this will NOT add the public key
84 * to any physical file (e.g., "~/.ssh/known_hosts") - use <code>addHostkeyToFile()</code> for that purpose.
85 * This method is designed to be used in a {@link ServerHostKeyVerifier}.
86 *
87 * @param hostnames a list of hostname patterns - at least one most be specified. Check out the
88 * OpenSSH sshd man page for a description of the pattern matching algorithm.
89 * @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
90 * @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
91 * @throws IOException
92 */
93 public void addHostkey(String hostnames[], String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
94 if(hostnames == null) {
95 throw new IllegalArgumentException("hostnames may not be null");
96 }
97
98 if("ssh-rsa".equals(serverHostKeyAlgorithm)) {
99 RSAPublicKey rpk = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey);
100
101 synchronized(publicKeys) {
102 publicKeys.add(new KnownHostsEntry(hostnames, rpk));
103 }
104 }
105 else if("ssh-dss".equals(serverHostKeyAlgorithm)) {
106 DSAPublicKey dpk = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey);
107
108 synchronized(publicKeys) {
109 publicKeys.add(new KnownHostsEntry(hostnames, dpk));
110 }
111 }
112 else {
113 throw new IOException(String.format("Unknown host key type %s", serverHostKeyAlgorithm));
114 }
115 }
116
117 /**
118 * Parses the given known_hosts data and adds entries to the database.
119 *
120 * @param knownHostsData
121 * @throws IOException
122 */
123 public void addHostkeys(char[] knownHostsData) throws IOException {
124 initialize(knownHostsData);
125 }
126
127 /**
128 * Parses the given known_hosts file and adds entries to the database.
129 *
130 * @param knownHosts
131 * @throws IOException
132 */
133 public void addHostkeys(File knownHosts) throws IOException {
134 initialize(knownHosts);
135 }
136
137 /**
138 * Generate the hashed representation of the given hostname. Useful for adding entries
139 * with hashed hostnames to a known_hosts file. (see -H option of OpenSSH key-gen).
140 *
141 * @param hostname
142 * @return the hashed representation, e.g., "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
143 */
144 public static String createHashedHostname(String hostname) throws IOException {
145 SHA1 sha1 = new SHA1();
146
147 byte[] salt = new byte[sha1.getDigestLength()];
148
149 new SecureRandom().nextBytes(salt);
150
151 byte[] hash;
152 try {
153 hash = hmacSha1Hash(salt, hostname);
154 }
155 catch(IOException e) {
156 throw new IOException(e);
157 }
158
159 String base64_salt = new String(Base64.encode(salt));
160 String base64_hash = new String(Base64.encode(hash));
161
162 return String.format("|1|%s|%s", base64_salt, base64_hash);
163 }
164
165 private static byte[] hmacSha1Hash(byte[] salt, String hostname) throws IOException {
166 SHA1 sha1 = new SHA1();
167
168 if(salt.length != sha1.getDigestLength()) {
169 throw new IllegalArgumentException("Salt has wrong length (" + salt.length + ")");
170 }
171 try {
172 HMAC hmac = new HMAC(sha1, salt, salt.length);
173
174 hmac.update(StringEncoder.GetBytes(hostname));
175
176 byte[] dig = new byte[hmac.getDigestLength()];
177
178 hmac.digest(dig);
179
180 return dig;
181 }
182 catch(DigestException e) {
183 throw new IOException(e);
184 }
185 }
186
187 private boolean checkHashed(String entry, String hostname) {
188 if(entry.startsWith("|1|") == false) {
189 return false;
190 }
191
192 int delim_idx = entry.indexOf('|', 3);
193
194 if(delim_idx == -1) {
195 return false;
196 }
197
198 String salt_base64 = entry.substring(3, delim_idx);
199 String hash_base64 = entry.substring(delim_idx + 1);
200
201 byte[] salt;
202 byte[] hash;
203
204 try {
205 salt = Base64.decode(salt_base64.toCharArray());
206 hash = Base64.decode(hash_base64.toCharArray());
207 }
208 catch(IOException e) {
209 return false;
210 }
211
212 SHA1 sha1 = new SHA1();
213
214 if(salt.length != sha1.getDigestLength()) {
215 return false;
216 }
217
218 byte[] dig = new byte[0];
219 try {
220 dig = hmacSha1Hash(salt, hostname);
221 }
222 catch(IOException e) {
223 return false;
224 }
225
226 for(int i = 0; i < dig.length; i++) {
227 if(dig[i] != hash[i]) {
228 return false;
229 }
230 }
231
232 return true;
233 }
234
235 private int checkKey(String remoteHostname, Object remoteKey) {
236 int result = HOSTKEY_IS_NEW;
237
238 synchronized(publicKeys) {
239 for(KnownHostsEntry ke : publicKeys) {
240 if(hostnameMatches(ke.patterns, remoteHostname) == false) {
241 continue;
242 }
243
244 boolean res = matchKeys(ke.key, remoteKey);
245
246 if(res == true) {
247 return HOSTKEY_IS_OK;
248 }
249
250 result = HOSTKEY_HAS_CHANGED;
251 }
252 }
253 return result;
254 }
255
256 private List<Object> getAllKeys(String hostname) {
257 List<Object> keys = new ArrayList<Object>();
258
259 synchronized(publicKeys) {
260 for(KnownHostsEntry ke : publicKeys) {
261 if(hostnameMatches(ke.patterns, hostname) == false) {
262 continue;
263 }
264
265 keys.add(ke.key);
266 }
267 }
268
269 return keys;
270 }
271
272 /**
273 * Try to find the preferred order of hostkey algorithms for the given hostname.
274 * Based on the type of hostkey that is present in the internal database
275 * (i.e., either <code>ssh-rsa</code> or <code>ssh-dss</code>)
276 * an ordered list of hostkey algorithms is returned which can be passed
277 * to <code>Connection.setServerHostKeyAlgorithms</code>.
278 *
279 * @param hostname
280 * @return <code>null</code> if no key for the given hostname is present or
281 * there are keys of multiple types present for the given hostname. Otherwise,
282 * an array with hostkey algorithms is returned (i.e., an array of length 2).
283 */
284 public String[] getPreferredServerHostkeyAlgorithmOrder(String hostname) {
285 String[] algos = recommendHostkeyAlgorithms(hostname);
286
287 if(algos != null) {
288 return algos;
289 }
290
291 InetAddress[] ipAdresses;
292
293 try {
294 ipAdresses = InetAddress.getAllByName(hostname);
295 }
296 catch(UnknownHostException e) {
297 return null;
298 }
299
300 for(int i = 0; i < ipAdresses.length; i++) {
301 algos = recommendHostkeyAlgorithms(ipAdresses[i].getHostAddress());
302
303 if(algos != null) {
304 return algos;
305 }
306 }
307
308 return null;
309 }
310
311 private boolean hostnameMatches(String[] hostpatterns, String hostname) {
312 boolean isMatch = false;
313 boolean negate;
314
315 hostname = hostname.toLowerCase();
316
317 for(int k = 0; k < hostpatterns.length; k++) {
318 if(hostpatterns[k] == null) {
319 continue;
320 }
321
322 String pattern;
323
324 /* In contrast to OpenSSH we also allow negated hash entries (as well as hashed
325 * entries in lines with multiple entries).
326 */
327
328 if((hostpatterns[k].length() > 0) && (hostpatterns[k].charAt(0) == '!')) {
329 pattern = hostpatterns[k].substring(1);
330 negate = true;
331 }
332 else {
333 pattern = hostpatterns[k];
334 negate = false;
335 }
336
337 /* Optimize, no need to check this entry */
338
339 if((isMatch) && (negate == false)) {
340 continue;
341 }
342
343 /* Now compare */
344
345 if(pattern.charAt(0) == '|') {
346 if(checkHashed(pattern, hostname)) {
347 if(negate) {
348 return false;
349 }
350 isMatch = true;
351 }
352 }
353 else {
354 pattern = pattern.toLowerCase();
355
356 if((pattern.indexOf('?') != -1) || (pattern.indexOf('*') != -1)) {
357 if(pseudoRegex(pattern.toCharArray(), 0, hostname.toCharArray(), 0)) {
358 if(negate) {
359 return false;
360 }
361 isMatch = true;
362 }
363 }
364 else if(pattern.compareTo(hostname) == 0) {
365 if(negate) {
366 return false;
367 }
368 isMatch = true;
369 }
370 }
371 }
372
373 return isMatch;
374 }
375
376 private void initialize(char[] knownHostsData) throws IOException {
377 BufferedReader br = new BufferedReader(new CharArrayReader(knownHostsData));
378
379 while(true) {
380 String line = br.readLine();
381
382 if(line == null) {
383 break;
384 }
385
386 line = line.trim();
387
388 if(line.startsWith("#")) {
389 continue;
390 }
391
392 String[] arr = line.split(" ");
393
394 if(arr.length >= 3) {
395 if((arr[1].compareTo("ssh-rsa") == 0) || (arr[1].compareTo("ssh-dss") == 0)) {
396 String[] hostnames = arr[0].split(",");
397
398 byte[] msg = Base64.decode(arr[2].toCharArray());
399
400 try {
401 addHostkey(hostnames, arr[1], msg);
402 }
403 catch(IOException e) {
404 continue;
405 }
406 }
407 }
408 }
409 }
410
411 private void initialize(File knownHosts) throws IOException {
412 char[] buff = new char[512];
413
414 CharArrayWriter cw = new CharArrayWriter();
415
416 knownHosts.createNewFile();
417
418 FileReader fr = new FileReader(knownHosts);
419
420 while(true) {
421 int len = fr.read(buff);
422 if(len < 0) {
423 break;
424 }
425 cw.write(buff, 0, len);
426 }
427
428 fr.close();
429
430 initialize(cw.toCharArray());
431 }
432
433 private boolean matchKeys(Object key1, Object key2) {
434 if((key1 instanceof RSAPublicKey) && (key2 instanceof RSAPublicKey)) {
435 RSAPublicKey savedRSAKey = (RSAPublicKey) key1;
436 RSAPublicKey remoteRSAKey = (RSAPublicKey) key2;
437
438 if(savedRSAKey.getE().equals(remoteRSAKey.getE()) == false) {
439 return false;
440 }
441
442 if(savedRSAKey.getN().equals(remoteRSAKey.getN()) == false) {
443 return false;
444 }
445
446 return true;
447 }
448
449 if((key1 instanceof DSAPublicKey) && (key2 instanceof DSAPublicKey)) {
450 DSAPublicKey savedDSAKey = (DSAPublicKey) key1;
451 DSAPublicKey remoteDSAKey = (DSAPublicKey) key2;
452
453 if(savedDSAKey.getG().equals(remoteDSAKey.getG()) == false) {
454 return false;
455 }
456
457 if(savedDSAKey.getP().equals(remoteDSAKey.getP()) == false) {
458 return false;
459 }
460
461 if(savedDSAKey.getQ().equals(remoteDSAKey.getQ()) == false) {
462 return false;
463 }
464
465 if(savedDSAKey.getY().equals(remoteDSAKey.getY()) == false) {
466 return false;
467 }
468
469 return true;
470 }
471
472 return false;
473 }
474
475 private boolean pseudoRegex(char[] pattern, int i, char[] match, int j) {
476 /* This matching logic is equivalent to the one present in OpenSSH 4.1 */
477
478 while(true) {
479 /* Are we at the end of the pattern? */
480
481 if(pattern.length == i) {
482 return (match.length == j);
483 }
484
485 if(pattern[i] == '*') {
486 i++;
487
488 if(pattern.length == i) {
489 return true;
490 }
491
492 if((pattern[i] != '*') && (pattern[i] != '?')) {
493 while(true) {
494 if((pattern[i] == match[j]) && pseudoRegex(pattern, i + 1, match, j + 1)) {
495 return true;
496 }
497 j++;
498 if(match.length == j) {
499 return false;
500 }
501 }
502 }
503
504 while(true) {
505 if(pseudoRegex(pattern, i, match, j)) {
506 return true;
507 }
508 j++;
509 if(match.length == j) {
510 return false;
511 }
512 }
513 }
514
515 if(match.length == j) {
516 return false;
517 }
518
519 if((pattern[i] != '?') && (pattern[i] != match[j])) {
520 return false;
521 }
522
523 i++;
524 j++;
525 }
526 }
527
528 private String[] recommendHostkeyAlgorithms(String hostname) {
529 String preferredAlgo = null;
530
531 List<Object> keys = getAllKeys(hostname);
532
533 for(Object key : keys) {
534 String thisAlgo;
535
536 if(key instanceof RSAPublicKey) {
537 thisAlgo = "ssh-rsa";
538 }
539 else if(key instanceof DSAPublicKey) {
540 thisAlgo = "ssh-dss";
541 }
542 else {
543 continue;
544 }
545
546 if(preferredAlgo != null) {
547 /* If we find different key types, then return null */
548
549 if(preferredAlgo.compareTo(thisAlgo) != 0) {
550 return null;
551 }
552 }
553 else {
554 preferredAlgo = thisAlgo;
555 }
556 }
557
558 /* If we did not find anything that we know of, return null */
559
560 if(preferredAlgo == null) {
561 return null;
562 }
563
564 /* Now put the preferred algo to the start of the array.
565 * You may ask yourself why we do it that way - basically, we could just
566 * return only the preferred algorithm: since we have a saved key of that
567 * type (sent earlier from the remote host), then that should work out.
568 * However, imagine that the server is (for whatever reasons) not offering
569 * that type of hostkey anymore (e.g., "ssh-rsa" was disabled and
570 * now "ssh-dss" is being used). If we then do not let the server send us
571 * a fresh key of the new type, then we shoot ourself into the foot:
572 * the connection cannot be established and hence the user cannot decide
573 * if he/she wants to accept the new key.
574 */
575
576 if(preferredAlgo.equals("ssh-rsa")) {
577 return new String[]{"ssh-rsa", "ssh-dss"};
578 }
579
580 return new String[]{"ssh-dss", "ssh-rsa"};
581 }
582
583 /**
584 * Checks the internal hostkey database for the given hostkey.
585 * If no matching key can be found, then the hostname is resolved to an IP address
586 * and the search is repeated using that IP address.
587 *
588 * @param hostname the server's hostname, will be matched with all hostname patterns
589 * @param serverHostKeyAlgorithm type of hostkey, either <code>ssh-rsa</code> or <code>ssh-dss</code>
590 * @param serverHostKey the key blob
591 * @return <ul>
592 * <li><code>HOSTKEY_IS_OK</code>: the given hostkey matches an entry for the given hostname</li>
593 * <li><code>HOSTKEY_IS_NEW</code>: no entries found for this hostname and this type of hostkey</li>
594 * <li><code>HOSTKEY_HAS_CHANGED</code>: hostname is known, but with another key of the same type
595 * (man-in-the-middle attack?)</li>
596 * </ul>
597 * @throws IOException if the supplied key blob cannot be parsed or does not match the given hostkey type.
598 */
599 public int verifyHostkey(String hostname, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
600 Object remoteKey;
601
602 if("ssh-rsa".equals(serverHostKeyAlgorithm)) {
603 remoteKey = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey);
604 }
605 else if("ssh-dss".equals(serverHostKeyAlgorithm)) {
606 remoteKey = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey);
607 }
608 else {
609 throw new IllegalArgumentException("Unknown hostkey type " + serverHostKeyAlgorithm);
610 }
611
612 int result = checkKey(hostname, remoteKey);
613
614 if(result == HOSTKEY_IS_OK) {
615 return result;
616 }
617
618 InetAddress[] ipAdresses;
619
620 try {
621 ipAdresses = InetAddress.getAllByName(hostname);
622 }
623 catch(UnknownHostException e) {
624 return result;
625 }
626
627 for(int i = 0; i < ipAdresses.length; i++) {
628 int newresult = checkKey(ipAdresses[i].getHostAddress(), remoteKey);
629
630 if(newresult == HOSTKEY_IS_OK) {
631 return newresult;
632 }
633
634 if(newresult == HOSTKEY_HAS_CHANGED) {
635 result = HOSTKEY_HAS_CHANGED;
636 }
637 }
638
639 return result;
640 }
641
642 /**
643 * Adds a single public key entry to the a known_hosts file.
644 * This method is designed to be used in a {@link ServerHostKeyVerifier}.
645 *
646 * @param knownHosts the file where the publickey entry will be appended.
647 * @param hostnames a list of hostname patterns - at least one most be specified. Check out the
648 * OpenSSH sshd man page for a description of the pattern matching algorithm.
649 * @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
650 * @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
651 * @throws IOException
652 */
653 public static void addHostkeyToFile(File knownHosts, String[] hostnames, String serverHostKeyAlgorithm,
654 byte[] serverHostKey) throws IOException {
655 if((hostnames == null) || (hostnames.length == 0)) {
656 throw new IllegalArgumentException("Need at least one hostname specification");
657 }
658
659 if((serverHostKeyAlgorithm == null) || (serverHostKey == null)) {
660 throw new IllegalArgumentException();
661 }
662
663 CharArrayWriter writer = new CharArrayWriter();
664
665 for(int i = 0; i < hostnames.length; i++) {
666 if(i != 0) {
667 writer.write(',');
668 }
669 writer.write(hostnames[i]);
670 }
671
672 writer.write(' ');
673 writer.write(serverHostKeyAlgorithm);
674 writer.write(' ');
675 writer.write(Base64.encode(serverHostKey));
676 writer.write("\n");
677
678 char[] entry = writer.toCharArray();
679
680 RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");
681
682 long len = raf.length();
683
684 if(len > 0) {
685 raf.seek(len - 1);
686 int last = raf.read();
687 if(last != '\n') {
688 raf.write('\n');
689 }
690 }
691
692 raf.write(StringEncoder.GetBytes(new String(entry)));
693 raf.close();
694 }
695
696 /**
697 * Generates a "raw" fingerprint of a hostkey.
698 *
699 * @param type either "md5" or "sha1"
700 * @param keyType either "ssh-rsa" or "ssh-dss"
701 * @param hostkey the hostkey
702 * @return the raw fingerprint
703 */
704 static private byte[] rawFingerPrint(String type, String keyType, byte[] hostkey) throws IOException {
705 Digest dig;
706
707 if("md5".equals(type)) {
708 dig = new MD5();
709 }
710 else if("sha1".equals(type)) {
711 dig = new SHA1();
712 }
713 else {
714 throw new IllegalArgumentException("Unknown hash type " + type);
715 }
716
717 if("ssh-rsa".equals(keyType)) {
718 }
719 else if("ssh-dss".equals(keyType)) {
720 }
721 else {
722 throw new IllegalArgumentException("Unknown key type " + keyType);
723 }
724
725 if(hostkey == null) {
726 throw new IllegalArgumentException("hostkey is null");
727 }
728
729 dig.update(hostkey);
730 byte[] res = new byte[dig.getDigestLength()];
731 try {
732 dig.digest(res);
733 }
734 catch(DigestException e) {
735 throw new IOException(e);
736 }
737 return res;
738 }
739
740 /**
741 * Convert a raw fingerprint to hex representation (XX:YY:ZZ...).
742 *
743 * @param fingerprint raw fingerprint
744 * @return the hex representation
745 */
746 static private String rawToHexFingerprint(byte[] fingerprint) {
747 final char[] alpha = "0123456789abcdef".toCharArray();
748
749 StringBuilder sb = new StringBuilder();
750
751 for(int i = 0; i < fingerprint.length; i++) {
752 if(i != 0) {
753 sb.append(':');
754 }
755 int b = fingerprint[i] & 0xff;
756 sb.append(alpha[b >> 4]);
757 sb.append(alpha[b & 15]);
758 }
759
760 return sb.toString();
761 }
762
763 /**
764 * Convert a raw fingerprint to bubblebabble representation.
765 *
766 * @param raw raw fingerprint
767 * @return the bubblebabble representation
768 */
769 static private String rawToBubblebabbleFingerprint(byte[] raw) {
770 final char[] v = "aeiouy".toCharArray();
771 final char[] c = "bcdfghklmnprstvzx".toCharArray();
772
773 StringBuilder sb = new StringBuilder();
774
775 int seed = 1;
776
777 int rounds = (raw.length / 2) + 1;
778
779 sb.append('x');
780
781 for(int i = 0; i < rounds; i++) {
782 if(((i + 1) < rounds) || ((raw.length) % 2 != 0)) {
783 sb.append(v[(((raw[2 * i] >> 6) & 3) + seed) % 6]);
784 sb.append(c[(raw[2 * i] >> 2) & 15]);
785 sb.append(v[((raw[2 * i] & 3) + (seed / 6)) % 6]);
786
787 if((i + 1) < rounds) {
788 sb.append(c[(((raw[(2 * i) + 1])) >> 4) & 15]);
789 sb.append('-');
790 sb.append(c[(((raw[(2 * i) + 1]))) & 15]);
791 // As long as seed >= 0, seed will be >= 0 afterwards
792 seed = ((seed * 5) + (((raw[2 * i] & 0xff) * 7) + (raw[(2 * i) + 1] & 0xff))) % 36;
793 }
794 }
795 else {
796 sb.append(v[seed % 6]); // seed >= 0, therefore index positive
797 sb.append('x');
798 sb.append(v[seed / 6]);
799 }
800 }
801
802 sb.append('x');
803
804 return sb.toString();
805 }
806
807 /**
808 * Convert a ssh2 key-blob into a human readable hex fingerprint.
809 * Generated fingerprints are identical to those generated by OpenSSH.
810 * <p/>
811 * Example fingerprint: d0:cb:76:19:99:5a:03:fc:73:10:70:93:f2:44:63:47.
812 *
813 * @param keytype either "ssh-rsa" or "ssh-dss"
814 * @param publickey key blob
815 * @return Hex fingerprint
816 */
817 public static String createHexFingerprint(String keytype, byte[] publickey) throws IOException {
818 byte[] raw = rawFingerPrint("md5", keytype, publickey);
819 return rawToHexFingerprint(raw);
820 }
821
822 /**
823 * Convert a ssh2 key-blob into a human readable bubblebabble fingerprint.
824 * The used bubblebabble algorithm (taken from OpenSSH) generates fingerprints
825 * that are easier to remember for humans.
826 * <p/>
827 * Example fingerprint: xofoc-bubuz-cazin-zufyl-pivuk-biduk-tacib-pybur-gonar-hotat-lyxux.
828 *
829 * @param keytype either "ssh-rsa" or "ssh-dss"
830 * @param publickey key data
831 * @return Bubblebabble fingerprint
832 */
833 public static String createBubblebabbleFingerprint(String keytype, byte[] publickey) throws IOException {
834 byte[] raw = rawFingerPrint("sha1", keytype, publickey);
835 return rawToBubblebabbleFingerprint(raw);
836 }
837 }