1 2 package ch.ethz.ssh2.crypto.dh; 3 4 import java.math.BigInteger ; 5 import java.security.SecureRandom ; 6 7 import ch.ethz.ssh2.DHGexParameters; 8 import ch.ethz.ssh2.crypto.digest.HashForSSH2Types; 9 10 16 public class DhGroupExchange 17 { 18 19 20 private BigInteger p; 21 private BigInteger g; 22 23 24 25 private BigInteger e; 26 private BigInteger x; 27 28 29 30 private BigInteger f; 31 32 33 34 private BigInteger k; 35 36 public DhGroupExchange(BigInteger p, BigInteger g) 37 { 38 this.p = p; 39 this.g = g; 40 } 41 42 public void init(SecureRandom rnd) 43 { 44 k = null; 45 46 x = new BigInteger (p.bitLength() - 1, rnd); 47 e = g.modPow(x, p); 48 } 49 50 53 public BigInteger getE() 54 { 55 if (e == null) 56 throw new IllegalStateException ("Not initialized!"); 57 58 return e; 59 } 60 61 64 public BigInteger getK() 65 { 66 if (k == null) 67 throw new IllegalStateException ("Shared secret not yet known, need f first!"); 68 69 return k; 70 } 71 72 75 public void setF(BigInteger f) 76 { 77 if (e == null) 78 throw new IllegalStateException ("Not initialized!"); 79 80 BigInteger zero = BigInteger.valueOf(0); 81 82 if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0) 83 throw new IllegalArgumentException ("Invalid f specified!"); 84 85 this.f = f; 86 this.k = f.modPow(x, p); 87 } 88 89 public byte[] calculateH(byte[] clientversion, byte[] serverversion, byte[] clientKexPayload, 90 byte[] serverKexPayload, byte[] hostKey, DHGexParameters para) 91 { 92 HashForSSH2Types hash = new HashForSSH2Types("SHA1"); 93 94 hash.updateByteString(clientversion); 95 hash.updateByteString(serverversion); 96 hash.updateByteString(clientKexPayload); 97 hash.updateByteString(serverKexPayload); 98 hash.updateByteString(hostKey); 99 if (para.getMin_group_len() > 0) 100 hash.updateUINT32(para.getMin_group_len()); 101 hash.updateUINT32(para.getPref_group_len()); 102 if (para.getMax_group_len() > 0) 103 hash.updateUINT32(para.getMax_group_len()); 104 hash.updateBigInt(p); 105 hash.updateBigInt(g); 106 hash.updateBigInt(e); 107 hash.updateBigInt(f); 108 hash.updateBigInt(k); 109 110 return hash.getDigest(); 111 } 112 } 113 | Popular Tags |