PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/SharpSSH/jsch/KeyPair.cs

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