PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/sshxcute/src/com/jcraft/jsch/KeyPair.java

http://sshxcute.googlecode.com/
Java | 665 lines | 548 code | 68 blank | 49 comment | 104 complexity | ca2a3a7f03498ea68fbb97d87720d991 MD5 | raw file
  1. /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
  2. /*
  3. Copyright (c) 2002-2009 ymnk, JCraft,Inc. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in
  10. the documentation and/or other materials provided with the distribution.
  11. 3. The names of the authors may not be used to endorse or promote products
  12. derived from this software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  14. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  15. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  16. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. package com.jcraft.jsch;
  25. import java.io.FileOutputStream;
  26. import java.io.FileInputStream;
  27. import java.io.File;
  28. public abstract class KeyPair{
  29. public static final int ERROR=0;
  30. public static final int DSA=1;
  31. public static final int RSA=2;
  32. public static final int UNKNOWN=3;
  33. static final int VENDOR_OPENSSH=0;
  34. static final int VENDOR_FSECURE=1;
  35. int vendor=VENDOR_OPENSSH;
  36. private static final byte[] cr="\n".getBytes();
  37. public static KeyPair genKeyPair(JSch jsch, int type) throws JSchException{
  38. return genKeyPair(jsch, type, 1024);
  39. }
  40. public static KeyPair genKeyPair(JSch jsch, int type, int key_size) throws JSchException{
  41. KeyPair kpair=null;
  42. if(type==DSA){ kpair=new KeyPairDSA(jsch); }
  43. else if(type==RSA){ kpair=new KeyPairRSA(jsch); }
  44. if(kpair!=null){
  45. kpair.generate(key_size);
  46. }
  47. return kpair;
  48. }
  49. abstract void generate(int key_size) throws JSchException;
  50. abstract byte[] getBegin();
  51. abstract byte[] getEnd();
  52. abstract int getKeySize();
  53. JSch jsch=null;
  54. private Cipher cipher;
  55. private HASH hash;
  56. private Random random;
  57. private byte[] passphrase;
  58. public KeyPair(JSch jsch){
  59. this.jsch=jsch;
  60. }
  61. static byte[][] header={"Proc-Type: 4,ENCRYPTED".getBytes(),
  62. "DEK-Info: DES-EDE3-CBC,".getBytes()};
  63. abstract byte[] getPrivateKey();
  64. public void writePrivateKey(java.io.OutputStream out){
  65. byte[] plain=getPrivateKey();
  66. byte[][] _iv=new byte[1][];
  67. byte[] encoded=encrypt(plain, _iv);
  68. if(encoded!=plain)
  69. Util.bzero(plain);
  70. byte[] iv=_iv[0];
  71. byte[] prv=Util.toBase64(encoded, 0, encoded.length);
  72. try{
  73. out.write(getBegin()); out.write(cr);
  74. if(passphrase!=null){
  75. out.write(header[0]); out.write(cr);
  76. out.write(header[1]);
  77. for(int i=0; i<iv.length; i++){
  78. out.write(b2a((byte)((iv[i]>>>4)&0x0f)));
  79. out.write(b2a((byte)(iv[i]&0x0f)));
  80. }
  81. out.write(cr);
  82. out.write(cr);
  83. }
  84. int i=0;
  85. while(i<prv.length){
  86. if(i+64<prv.length){
  87. out.write(prv, i, 64);
  88. out.write(cr);
  89. i+=64;
  90. continue;
  91. }
  92. out.write(prv, i, prv.length-i);
  93. out.write(cr);
  94. break;
  95. }
  96. out.write(getEnd()); out.write(cr);
  97. //out.close();
  98. }
  99. catch(Exception e){
  100. }
  101. }
  102. private static byte[] space=" ".getBytes();
  103. abstract byte[] getKeyTypeName();
  104. public abstract int getKeyType();
  105. public byte[] getPublicKeyBlob(){ return publickeyblob; }
  106. public void writePublicKey(java.io.OutputStream out, String comment){
  107. byte[] pubblob=getPublicKeyBlob();
  108. byte[] pub=Util.toBase64(pubblob, 0, pubblob.length);
  109. try{
  110. out.write(getKeyTypeName()); out.write(space);
  111. out.write(pub, 0, pub.length); out.write(space);
  112. out.write(comment.getBytes());
  113. out.write(cr);
  114. }
  115. catch(Exception e){
  116. }
  117. }
  118. public void writePublicKey(String name, String comment) throws java.io.FileNotFoundException, java.io.IOException{
  119. FileOutputStream fos=new FileOutputStream(name);
  120. writePublicKey(fos, comment);
  121. fos.close();
  122. }
  123. public void writeSECSHPublicKey(java.io.OutputStream out, String comment){
  124. byte[] pubblob=getPublicKeyBlob();
  125. byte[] pub=Util.toBase64(pubblob, 0, pubblob.length);
  126. try{
  127. out.write("---- BEGIN SSH2 PUBLIC KEY ----".getBytes()); out.write(cr);
  128. out.write(("Comment: \""+comment+"\"").getBytes()); out.write(cr);
  129. int index=0;
  130. while(index<pub.length){
  131. int len=70;
  132. if((pub.length-index)<len)len=pub.length-index;
  133. out.write(pub, index, len); out.write(cr);
  134. index+=len;
  135. }
  136. out.write("---- END SSH2 PUBLIC KEY ----".getBytes()); out.write(cr);
  137. }
  138. catch(Exception e){
  139. }
  140. }
  141. public void writeSECSHPublicKey(String name, String comment) throws java.io.FileNotFoundException, java.io.IOException{
  142. FileOutputStream fos=new FileOutputStream(name);
  143. writeSECSHPublicKey(fos, comment);
  144. fos.close();
  145. }
  146. public void writePrivateKey(String name) throws java.io.FileNotFoundException, java.io.IOException{
  147. FileOutputStream fos=new FileOutputStream(name);
  148. writePrivateKey(fos);
  149. fos.close();
  150. }
  151. public String getFingerPrint(){
  152. if(hash==null) hash=genHash();
  153. byte[] kblob=getPublicKeyBlob();
  154. if(kblob==null) return null;
  155. return getKeySize()+" "+Util.getFingerPrint(hash, kblob);
  156. }
  157. private byte[] encrypt(byte[] plain, byte[][] _iv){
  158. if(passphrase==null) return plain;
  159. if(cipher==null) cipher=genCipher();
  160. byte[] iv=_iv[0]=new byte[cipher.getIVSize()];
  161. if(random==null) random=genRandom();
  162. random.fill(iv, 0, iv.length);
  163. byte[] key=genKey(passphrase, iv);
  164. byte[] encoded=plain;
  165. // PKCS#5Padding
  166. {
  167. //int bsize=cipher.getBlockSize();
  168. int bsize=cipher.getIVSize();
  169. byte[] foo=new byte[(encoded.length/bsize+1)*bsize];
  170. System.arraycopy(encoded, 0, foo, 0, encoded.length);
  171. int padding=bsize-encoded.length%bsize;
  172. for(int i=foo.length-1; (foo.length-padding)<=i; i--){
  173. foo[i]=(byte)padding;
  174. }
  175. encoded=foo;
  176. }
  177. try{
  178. cipher.init(Cipher.ENCRYPT_MODE, key, iv);
  179. cipher.update(encoded, 0, encoded.length, encoded, 0);
  180. }
  181. catch(Exception e){
  182. //System.err.println(e);
  183. }
  184. Util.bzero(key);
  185. return encoded;
  186. }
  187. abstract boolean parse(byte[] data);
  188. private byte[] decrypt(byte[] data, byte[] passphrase, byte[] iv){
  189. /*
  190. if(iv==null){ // FSecure
  191. iv=new byte[8];
  192. for(int i=0; i<iv.length; i++)iv[i]=0;
  193. }
  194. */
  195. try{
  196. byte[] key=genKey(passphrase, iv);
  197. cipher.init(Cipher.DECRYPT_MODE, key, iv);
  198. Util.bzero(key);
  199. byte[] plain=new byte[data.length];
  200. cipher.update(data, 0, data.length, plain, 0);
  201. return plain;
  202. }
  203. catch(Exception e){
  204. //System.err.println(e);
  205. }
  206. return null;
  207. }
  208. int writeSEQUENCE(byte[] buf, int index, int len){
  209. buf[index++]=0x30;
  210. index=writeLength(buf, index, len);
  211. return index;
  212. }
  213. int writeINTEGER(byte[] buf, int index, byte[] data){
  214. buf[index++]=0x02;
  215. index=writeLength(buf, index, data.length);
  216. System.arraycopy(data, 0, buf, index, data.length);
  217. index+=data.length;
  218. return index;
  219. }
  220. int countLength(int len){
  221. int i=1;
  222. if(len<=0x7f) return i;
  223. while(len>0){
  224. len>>>=8;
  225. i++;
  226. }
  227. return i;
  228. }
  229. int writeLength(byte[] data, int index, int len){
  230. int i=countLength(len)-1;
  231. if(i==0){
  232. data[index++]=(byte)len;
  233. return index;
  234. }
  235. data[index++]=(byte)(0x80|i);
  236. int j=index+i;
  237. while(i>0){
  238. data[index+i-1]=(byte)(len&0xff);
  239. len>>>=8;
  240. i--;
  241. }
  242. return j;
  243. }
  244. private Random genRandom(){
  245. if(random==null){
  246. try{
  247. Class c=Class.forName(jsch.getConfig("random"));
  248. random=(Random)(c.newInstance());
  249. }
  250. catch(Exception e){ System.err.println("connect: random "+e); }
  251. }
  252. return random;
  253. }
  254. private HASH genHash(){
  255. try{
  256. Class c=Class.forName(jsch.getConfig("md5"));
  257. hash=(HASH)(c.newInstance());
  258. hash.init();
  259. }
  260. catch(Exception e){
  261. }
  262. return hash;
  263. }
  264. private Cipher genCipher(){
  265. try{
  266. Class c;
  267. c=Class.forName(jsch.getConfig("3des-cbc"));
  268. cipher=(Cipher)(c.newInstance());
  269. }
  270. catch(Exception e){
  271. }
  272. return cipher;
  273. }
  274. /*
  275. hash is MD5
  276. h(0) <- hash(passphrase, iv);
  277. h(n) <- hash(h(n-1), passphrase, iv);
  278. key <- (h(0),...,h(n))[0,..,key.length];
  279. */
  280. synchronized byte[] genKey(byte[] passphrase, byte[] iv){
  281. if(cipher==null) cipher=genCipher();
  282. if(hash==null) hash=genHash();
  283. byte[] key=new byte[cipher.getBlockSize()];
  284. int hsize=hash.getBlockSize();
  285. byte[] hn=new byte[key.length/hsize*hsize+
  286. (key.length%hsize==0?0:hsize)];
  287. try{
  288. byte[] tmp=null;
  289. if(vendor==VENDOR_OPENSSH){
  290. for(int index=0; index+hsize<=hn.length;){
  291. if(tmp!=null){ hash.update(tmp, 0, tmp.length); }
  292. hash.update(passphrase, 0, passphrase.length);
  293. hash.update(iv, 0, iv.length);
  294. tmp=hash.digest();
  295. System.arraycopy(tmp, 0, hn, index, tmp.length);
  296. index+=tmp.length;
  297. }
  298. System.arraycopy(hn, 0, key, 0, key.length);
  299. }
  300. else if(vendor==VENDOR_FSECURE){
  301. for(int index=0; index+hsize<=hn.length;){
  302. if(tmp!=null){ hash.update(tmp, 0, tmp.length); }
  303. hash.update(passphrase, 0, passphrase.length);
  304. tmp=hash.digest();
  305. System.arraycopy(tmp, 0, hn, index, tmp.length);
  306. index+=tmp.length;
  307. }
  308. System.arraycopy(hn, 0, key, 0, key.length);
  309. }
  310. }
  311. catch(Exception e){
  312. System.err.println(e);
  313. }
  314. return key;
  315. }
  316. public void setPassphrase(String passphrase){
  317. if(passphrase==null || passphrase.length()==0){
  318. setPassphrase((byte[])null);
  319. }
  320. else{
  321. setPassphrase(Util.str2byte(passphrase));
  322. }
  323. }
  324. public void setPassphrase(byte[] passphrase){
  325. if(passphrase!=null && passphrase.length==0)
  326. passphrase=null;
  327. this.passphrase=passphrase;
  328. }
  329. private boolean encrypted=false;
  330. private byte[] data=null;
  331. private byte[] iv=null;
  332. private byte[] publickeyblob=null;
  333. public boolean isEncrypted(){ return encrypted; }
  334. public boolean decrypt(String _passphrase){
  335. if(_passphrase==null || _passphrase.length()==0){
  336. return !encrypted;
  337. }
  338. return decrypt(Util.str2byte(_passphrase));
  339. }
  340. public boolean decrypt(byte[] _passphrase){
  341. if(!encrypted){
  342. return true;
  343. }
  344. if(_passphrase==null){
  345. return !encrypted;
  346. }
  347. byte[] bar=new byte[_passphrase.length];
  348. System.arraycopy(_passphrase, 0, bar, 0, bar.length);
  349. _passphrase=bar;
  350. byte[] foo=decrypt(data, _passphrase, iv);
  351. Util.bzero(_passphrase);
  352. if(parse(foo)){
  353. encrypted=false;
  354. }
  355. return !encrypted;
  356. }
  357. public static KeyPair load(JSch jsch, String prvkey) throws JSchException{
  358. String pubkey=prvkey+".pub";
  359. if(!new File(pubkey).exists()){
  360. pubkey=null;
  361. }
  362. return load(jsch, prvkey, pubkey);
  363. }
  364. public static KeyPair load(JSch jsch, String prvkey, String pubkey) throws JSchException{
  365. byte[] iv=new byte[8]; // 8
  366. boolean encrypted=true;
  367. byte[] data=null;
  368. byte[] publickeyblob=null;
  369. int type=ERROR;
  370. int vendor=VENDOR_OPENSSH;
  371. try{
  372. File file=new File(prvkey);
  373. FileInputStream fis=new FileInputStream(prvkey);
  374. byte[] buf=new byte[(int)(file.length())];
  375. int len=0;
  376. while(true){
  377. int i=fis.read(buf, len, buf.length-len);
  378. if(i<=0)
  379. break;
  380. len+=i;
  381. }
  382. fis.close();
  383. int i=0;
  384. while(i<len){
  385. if(buf[i]=='B'&& buf[i+1]=='E'&& buf[i+2]=='G'&& buf[i+3]=='I'){
  386. i+=6;
  387. if(buf[i]=='D'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=DSA; }
  388. else if(buf[i]=='R'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=RSA; }
  389. else if(buf[i]=='S'&& buf[i+1]=='S'&& buf[i+2]=='H'){ // FSecure
  390. type=UNKNOWN;
  391. vendor=VENDOR_FSECURE;
  392. }
  393. else{
  394. //System.err.println("invalid format: "+identity);
  395. throw new JSchException("invalid privatekey: "+prvkey);
  396. }
  397. i+=3;
  398. continue;
  399. }
  400. if(buf[i]=='C'&& buf[i+1]=='B'&& buf[i+2]=='C'&& buf[i+3]==','){
  401. i+=4;
  402. for(int ii=0; ii<iv.length; ii++){
  403. iv[ii]=(byte)(((a2b(buf[i++])<<4)&0xf0)+(a2b(buf[i++])&0xf));
  404. }
  405. continue;
  406. }
  407. if(buf[i]==0x0d &&
  408. i+1<buf.length && buf[i+1]==0x0a){
  409. i++;
  410. continue;
  411. }
  412. if(buf[i]==0x0a && i+1<buf.length){
  413. if(buf[i+1]==0x0a){ i+=2; break; }
  414. if(buf[i+1]==0x0d &&
  415. i+2<buf.length && buf[i+2]==0x0a){
  416. i+=3; break;
  417. }
  418. boolean inheader=false;
  419. for(int j=i+1; j<buf.length; j++){
  420. if(buf[j]==0x0a) break;
  421. //if(buf[j]==0x0d) break;
  422. if(buf[j]==':'){inheader=true; break;}
  423. }
  424. if(!inheader){
  425. i++;
  426. encrypted=false; // no passphrase
  427. break;
  428. }
  429. }
  430. i++;
  431. }
  432. if(type==ERROR){
  433. throw new JSchException("invalid privatekey: "+prvkey);
  434. }
  435. int start=i;
  436. while(i<len){
  437. if(buf[i]==0x0a){
  438. boolean xd=(buf[i-1]==0x0d);
  439. System.arraycopy(buf, i+1,
  440. buf,
  441. i-(xd ? 1 : 0),
  442. len-i-1-(xd ? 1 : 0)
  443. );
  444. if(xd)len--;
  445. len--;
  446. continue;
  447. }
  448. if(buf[i]=='-'){ break; }
  449. i++;
  450. }
  451. data=Util.fromBase64(buf, start, i-start);
  452. if(data.length>4 && // FSecure
  453. data[0]==(byte)0x3f &&
  454. data[1]==(byte)0x6f &&
  455. data[2]==(byte)0xf9 &&
  456. data[3]==(byte)0xeb){
  457. Buffer _buf=new Buffer(data);
  458. _buf.getInt(); // 0x3f6ff9be
  459. _buf.getInt();
  460. byte[]_type=_buf.getString();
  461. //System.err.println("type: "+new String(_type));
  462. byte[] _cipher=_buf.getString();
  463. String cipher=new String(_cipher);
  464. //System.err.println("cipher: "+cipher);
  465. if(cipher.equals("3des-cbc")){
  466. _buf.getInt();
  467. byte[] foo=new byte[data.length-_buf.getOffSet()];
  468. _buf.getByte(foo);
  469. data=foo;
  470. encrypted=true;
  471. throw new JSchException("unknown privatekey format: "+prvkey);
  472. }
  473. else if(cipher.equals("none")){
  474. _buf.getInt();
  475. _buf.getInt();
  476. encrypted=false;
  477. byte[] foo=new byte[data.length-_buf.getOffSet()];
  478. _buf.getByte(foo);
  479. data=foo;
  480. }
  481. }
  482. if(pubkey!=null){
  483. try{
  484. file=new File(pubkey);
  485. fis=new FileInputStream(pubkey);
  486. buf=new byte[(int)(file.length())];
  487. len=0;
  488. while(true){
  489. i=fis.read(buf, len, buf.length-len);
  490. if(i<=0)
  491. break;
  492. len+=i;
  493. }
  494. fis.close();
  495. if(buf.length>4 && // FSecure's public key
  496. buf[0]=='-' && buf[1]=='-' && buf[2]=='-' && buf[3]=='-'){
  497. boolean valid=true;
  498. i=0;
  499. do{i++;}while(buf.length>i && buf[i]!=0x0a);
  500. if(buf.length<=i) {valid=false;}
  501. while(valid){
  502. if(buf[i]==0x0a){
  503. boolean inheader=false;
  504. for(int j=i+1; j<buf.length; j++){
  505. if(buf[j]==0x0a) break;
  506. if(buf[j]==':'){inheader=true; break;}
  507. }
  508. if(!inheader){
  509. i++;
  510. break;
  511. }
  512. }
  513. i++;
  514. }
  515. if(buf.length<=i){valid=false;}
  516. start=i;
  517. while(valid && i<len){
  518. if(buf[i]==0x0a){
  519. System.arraycopy(buf, i+1, buf, i, len-i-1);
  520. len--;
  521. continue;
  522. }
  523. if(buf[i]=='-'){ break; }
  524. i++;
  525. }
  526. if(valid){
  527. publickeyblob=Util.fromBase64(buf, start, i-start);
  528. if(type==UNKNOWN){
  529. if(publickeyblob[8]=='d'){ type=DSA; }
  530. else if(publickeyblob[8]=='r'){ type=RSA; }
  531. }
  532. }
  533. }
  534. else{
  535. if(buf[0]=='s'&& buf[1]=='s'&& buf[2]=='h' && buf[3]=='-'){
  536. i=0;
  537. while(i<len){ if(buf[i]==' ')break; i++;} i++;
  538. if(i<len){
  539. start=i;
  540. while(i<len){ if(buf[i]==' ')break; i++;}
  541. publickeyblob=Util.fromBase64(buf, start, i-start);
  542. }
  543. }
  544. }
  545. }
  546. catch(Exception ee){
  547. }
  548. }
  549. }
  550. catch(Exception e){
  551. if(e instanceof JSchException) throw (JSchException)e;
  552. if(e instanceof Throwable)
  553. throw new JSchException(e.toString(), (Throwable)e);
  554. throw new JSchException(e.toString());
  555. }
  556. KeyPair kpair=null;
  557. if(type==DSA){ kpair=new KeyPairDSA(jsch); }
  558. else if(type==RSA){ kpair=new KeyPairRSA(jsch); }
  559. if(kpair!=null){
  560. kpair.encrypted=encrypted;
  561. kpair.publickeyblob=publickeyblob;
  562. kpair.vendor=vendor;
  563. if(encrypted){
  564. kpair.iv=iv;
  565. kpair.data=data;
  566. }
  567. else{
  568. if(kpair.parse(data)){
  569. return kpair;
  570. }
  571. else{
  572. throw new JSchException("invalid privatekey: "+prvkey);
  573. }
  574. }
  575. }
  576. return kpair;
  577. }
  578. static private byte a2b(byte c){
  579. if('0'<=c&&c<='9') return (byte)(c-'0');
  580. return (byte)(c-'a'+10);
  581. }
  582. static private byte b2a(byte c){
  583. if(0<=c&&c<=9) return (byte)(c+'0');
  584. return (byte)(c-10+'A');
  585. }
  586. public void dispose(){
  587. Util.bzero(passphrase);
  588. }
  589. public void finalize (){
  590. dispose();
  591. }
  592. }