Example usage for javax.crypto.spec DHParameterSpec DHParameterSpec

List of usage examples for javax.crypto.spec DHParameterSpec DHParameterSpec

Introduction

In this page you can find the example usage for javax.crypto.spec DHParameterSpec DHParameterSpec.

Prototype

public DHParameterSpec(BigInteger p, BigInteger g) 

Source Link

Document

Constructs a parameter set for Diffie-Hellman, using a prime modulus p and a base generator g.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");

    keyGen.initialize(dhParams, new SecureRandom());

    KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair aPair = keyGen.generateKeyPair();
    KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair bPair = keyGen.generateKeyPair();

    aKeyAgree.init(aPair.getPrivate());/*from w  w w .  j a  v  a 2  s . c om*/
    bKeyAgree.init(bPair.getPrivate());

    aKeyAgree.doPhase(bPair.getPublic(), true);
    bKeyAgree.doPhase(aPair.getPublic(), true);

    MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
    System.out.println(new String(hash.digest(aKeyAgree.generateSecret())));
    System.out.println(new String(hash.digest(bKeyAgree.generateSecret())));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");

    keyGen.initialize(dhParams, new SecureRandom());

    KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair aPair = keyGen.generateKeyPair();
    KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair bPair = keyGen.generateKeyPair();

    aKeyAgree.init(aPair.getPrivate());/*www  .ja va2s  . co  m*/
    bKeyAgree.init(bPair.getPrivate());

    aKeyAgree.doPhase(bPair.getPublic(), true);
    bKeyAgree.doPhase(aPair.getPublic(), true);

    MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
    System.out.println(new String(hash.digest(aKeyAgree.generateSecret())));
    System.out.println(new String(hash.digest(bKeyAgree.generateSecret())));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String s = "F488FD584E49DBCD20B49DE49107366B336C380D451D0F7C88"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111" + "2F78C7";
    BigInteger base = BigInteger.valueOf(2);
    BigInteger modulus = new BigInteger(s, 16);
    DHParameterSpec skipParameterSpec = new DHParameterSpec(modulus, base);

    KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH");
    kpg1.initialize(skipParameterSpec);//from   ww  w. java 2s. c o m
    KeyPair kp1 = kpg1.generateKeyPair();

    KeyAgreement ka1 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey1 = (DHPrivateKey) kp1.getPrivate();
    DHPublicKey publicKey1 = (DHPublicKey) kp1.getPublic();
    ka1.init(privateKey1);
    System.out.println("1 is using " + publicKey1.getY() + " for its public key");
    KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH");
    kpg2.initialize(skipParameterSpec);
    KeyPair kp2 = kpg2.generateKeyPair();

    KeyAgreement ka2 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey2 = (DHPrivateKey) kp2.getPrivate();
    DHPublicKey publicKey2 = (DHPublicKey) kp2.getPublic();
    ka2.init(privateKey2);
    System.out.println("2 is using " + publicKey2.getY() + " for its public key");
    ka1.doPhase(publicKey2, true);
    byte[] sharedKey1 = ka1.generateSecret();
    System.out.println("1 is using " + new BigInteger(1, sharedKey1) + " for its shared key");

    ka2.doPhase(publicKey1, true);
    byte[] sharedKey2 = ka2.generateSecret();
    System.out.println("2 is using " + new BigInteger(1, sharedKey2) + " for its shared key");
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String s = "F488FD584E49DBCD20B49DE49107366B336C380D451D0F7C88"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111" + "2F78C7";
    BigInteger base = BigInteger.valueOf(2);
    BigInteger modulous = new BigInteger(s, 16);
    DHParameterSpec skipParameterSpec = new DHParameterSpec(modulous, base);

    KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH");
    kpg1.initialize(skipParameterSpec);//from  w w w .  j av a 2s . c o m
    KeyPair kp1 = kpg1.generateKeyPair();

    KeyAgreement ka1 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey1 = (DHPrivateKey) kp1.getPrivate();
    DHPublicKey publicKey1 = (DHPublicKey) kp1.getPublic();
    ka1.init(privateKey1);
    System.out.println("1 is using " + publicKey1.getY() + " for its public key");

    KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH");
    kpg2.initialize(skipParameterSpec);
    KeyPair kp2 = kpg2.generateKeyPair();

    KeyAgreement ka2 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey2 = (DHPrivateKey) kp2.getPrivate();
    DHPublicKey publicKey2 = (DHPublicKey) kp2.getPublic();
    ka2.init(privateKey2);
    System.out.println("2 is using " + publicKey2.getY() + "for its public key");
    // Use the KeyAgreement object of 1 to generate its shared key
    ka1.doPhase(publicKey2, true);
    SecretKey sharedKey1 = ka1.generateSecret("DES");
    System.out.println("1 is using " + new String(sharedKey1.getEncoded()) + " as its DES session key");
    // Use the KeyAgreement object of 2 to generate its shared key
    ka2.doPhase(publicKey1, true);
    SecretKey sharedKey2 = ka2.generateSecret("DES");
    System.out.println("2 is using " + new String(sharedKey2.getEncoded()) + "as its DES session key");
}

From source file:MainClass.java

public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");

    DHParameterSpec param = new DHParameterSpec(p, g);
    kpg.initialize(param);/*from  w w  w . ja v a 2 s.co  m*/
    KeyPair kp = kpg.generateKeyPair();

    KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");

    DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class);
}

From source file:edu.internet2.middleware.openid.message.impl.AssociationRequestUnmarshaller.java

/** {@inheritDoc} */
public void unmarshallParameters(AssociationRequest request, ParameterMap parameters)
        throws UnmarshallingException {

    SessionType sessionType = SessionType.getType(parameters.get(Parameter.session_type.QNAME));
    request.setAssociationType(AssociationType.getType(parameters.get(Parameter.assoc_type.QNAME)));

    if (sessionType != null) {
        request.setSessionType(sessionType);

        if (sessionType.equals(SessionType.DH_SHA1) || sessionType.equals(SessionType.DH_SHA256)) {

            String encodedGen = parameters.get(Parameter.dh_gen.QNAME);
            String encodedModulus = parameters.get(Parameter.dh_modulus.QNAME);

            BigInteger gen;/*  w w w . j a va2s . co  m*/
            if (!DatatypeHelper.isEmpty(encodedGen)) {
                gen = new BigInteger(Base64.decodeBase64(encodedGen.getBytes()));
            } else {
                gen = OpenIDConstants.DEFAULT_DH_GEN;
            }

            BigInteger modulus;
            if (!DatatypeHelper.isEmpty(encodedModulus)) {
                modulus = new BigInteger(Base64.decodeBase64(encodedModulus.getBytes()));
            } else {
                modulus = OpenIDConstants.DEFAULT_DH_MODULUS;
            }

            DHParameterSpec dhParameters = new DHParameterSpec(modulus, gen);
            request.setDHParameters(dhParameters);

            String encodedKey = parameters.get(Parameter.dh_consumer_public.QNAME);
            if (!DatatypeHelper.isEmpty(encodedKey)) {
                try {
                    DHPublicKey publicKey = EncodingUtils.decodePublicKey(encodedKey, dhParameters);
                    request.setDHConsumerPublic(publicKey);
                } catch (NoSuchAlgorithmException e) {
                    throw new UnmarshallingException(e);
                } catch (InvalidKeySpecException e) {
                    throw new UnmarshallingException(e);
                }
            }

        }
    }

}

From source file:edu.internet2.middleware.openid.security.SxipAssociationTest.java

/**
 * Test MAC key encryptiong using a SHA-1 Association and the default DH parameter spec.
 * //from w w  w .j  ava 2  s. c  o m
 * @throws NoSuchAlgorithmException if algorithm does not exist
 * @throws InvalidKeySpecException if unable to build valid key spec
 */
public void testSHA1DefaultSpecMacKeyEncryption() throws NoSuchAlgorithmException, InvalidKeySpecException {
    AssociationType associationType = AssociationType.HMAC_SHA1;
    SessionType sessionType = SessionType.DH_SHA1;
    // DHParameterSpec parameterSpec = OpenIDConstants.DEFAULT_PARAMETER_SPEC;

    String encodedDHModulus = "ANz5OguIOXLsDhmYmsWizjEOHTdxfo2Vcbt2I3MYZuYe91ouJ4mLBX+YkcLiemOcPym2CBRYHNOyyjmG0mg3BVd9RcLn5S3IHHoXGHblzqdLFEi/368Ygo79JRnxTkXjgmY0rxlJ5bU1zIKaSDuKdiI+XUkKJX8Fvf8W8vsixYOr";
    String encodedDHGen = "Ag==";

    String encodedConsumerPublic = "AL8SSPKap+y4nAhDC5LrkRxuU/Fd6CtWnZ4xnIDnc9XfpbLH8i1ZONIld4VAZAxts+5Ij3mq1CYMGosC5BS1ooLdFj3yNGF2jkRS3WgNLgDMvlNnOfzjRbg3BcdAsJYlVuQz8FjlwQ8WYrzUPfyzcK7X7wLyVSS5nd7XCfKjIZGV";
    String encodedConsumerPrivate = "aPBA0T12u08cSahfgPhX0FMRd3DhU8N1y1lZSYapCmQEN7jac7HrsbqEHiKoyw/ndQz3myJ+jASJ/6Ve267hazLFbeDvY34p6uwkW/xypVS8cG9WWbhsLJrtDjyOfURf7l+OyFcu+C+71jAfA5txnpKV+olMsQqqHnfygnhxrQQ=";
    String encodedServerPublic = "daimW/oNGmkDIrGmy/1SSE3ECuDH5uLtn6BjVNboacDBpyLx0Hda4P6K6xN7sPJrMOJ4aUai2dSuRlleSN0VcZaaH+z02rhUpBiC8q6OFcBQcJnbo1yOjiFoNI+bMw81YlDOLQ+cpFxiFnH+HgQ1diL4YCC2Dg2mtkQiiQzijcE=";
    String encodedServerPrivate = "S0HBnYYGtByhSTgM6UBcRikfucZih5X7+4AER7Sv2gTQm6FYRmN5wVshoDR1R6jQ42yWZ/LVe4hp1oOfYuoyohzpWTCMTwSif5+IKxJ+KHFQ36ZVWwRBGcGdJFhIPXY1/DkqFl6lm/E0Iv982m9j2gMOmxXhX0h6UwS4n5t93AA=";

    String encodedMacKey = "6zvrrVkA4crhXE+VBNk0V1TfC/Q=";
    String encryptedMacKey = "RzOO/T1nO4B5GidVK9scjBeKXSQ=";

    BigInteger dhModulus = new BigInteger(Base64.decodeBase64(encodedDHModulus.getBytes()));
    BigInteger dhGen = new BigInteger(Base64.decodeBase64(encodedDHGen.getBytes()));
    DHParameterSpec parameterSpec = new DHParameterSpec(dhModulus, dhGen);

    DHPublicKey consumerPublic = EncodingUtils.decodePublicKey(encodedConsumerPublic, parameterSpec);
    DHPrivateKey consumerPrivate = EncodingUtils.decodePrivateKey(encodedConsumerPrivate, parameterSpec);
    DHPublicKey serverPublic = EncodingUtils.decodePublicKey(encodedServerPublic, parameterSpec);
    DHPrivateKey serverPrivate = EncodingUtils.decodePrivateKey(encodedServerPrivate, parameterSpec);

    SecretKey consumerSharedSecret = AssociationUtils.generateSharedSecret(consumerPrivate, serverPublic,
            sessionType.getAlgorithm());
    SecretKey serverSharedSecret = AssociationUtils.generateSharedSecret(serverPrivate, consumerPublic,
            sessionType.getAlgorithm());
    SecretKey macKey = EncodingUtils.decodeSecretKey(encodedMacKey, associationType.getAlgorithm());

    assertEquals(consumerSharedSecret, serverSharedSecret);
    assertEquals(encryptedMacKey,
            EncodingUtils.encodeSecretKey(AssociationUtils.encryptMacKey(macKey, consumerSharedSecret)));
}

From source file:org.pgptool.gui.encryption.implpgp.KeyGeneratorServicePgpImpl.java

@Override
public Key createNewKey(CreateKeyParams params) throws FieldValidationException {
    try {//from   ww  w  .j a v  a 2 s. c  o  m
        Preconditions.checkArgument(params != null, "params must not be null");
        assertParamsValid(params);

        // Create KeyPairs
        KeyPair dsaKp = getOrGenerateDsaKeyPair(DEFAULT_DSA_KEY_PARAMETERS);
        KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
        DHParameterSpec elParams = new DHParameterSpec(p, g);
        elgKpg.initialize(elParams);
        KeyPair elgKp = elgKpg.generateKeyPair();

        // Now let do some crazy stuff (I HAVE NO IDEA WHAT I AM DOING
        // HERE). BouncyCastle guys are not helping by changing API from
        // one version to another so often!!!!!!!
        PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
        PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());

        // PGPContentSignerBuilde
        // JCA
        // JcaPGPContentSignerBuilder keySignerBuilder = new
        // JcaPGPContentSignerBuilder(
        // dsaKeyPair.getPublicKey().getAlgorithm(),
        // HashAlgorithmTags.SHA256);

        // BC
        BcPGPContentSignerBuilder keySignerBuilderBC = new BcPGPContentSignerBuilder(
                dsaKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256);

        // PGPDigestCalculator
        // JCA
        // PGPDigestCalculator sha1Calc = new
        // JcaPGPDigestCalculatorProviderBuilder().build()
        // .get(HashAlgorithmTags.SHA256);

        // BC
        PGPDigestCalculator sha1CalcBC = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);

        // keyEncryptor
        // BC
        BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder(
                PGPEncryptedData.AES_256, sha1CalcBC);
        PBESecretKeyEncryptor keyEncryptorBC = encryptorBuilderBC.build(params.getPassphrase().toCharArray());

        // JCA
        // JcePBESecretKeyEncryptorBuilder encryptorBuilder = new
        // JcePBESecretKeyEncryptorBuilder(
        // PGPEncryptedData.AES_256, sha1Calc).setProvider("BC");
        // PBESecretKeyEncryptor keyEncryptor =
        // encryptorBuilder.build(params.getPassphrase().toCharArray());

        // keyRingGen
        String userName = params.getFullName() + " <" + params.getEmail() + ">";
        // JCA
        // PGPKeyRingGenerator keyRingGen = new
        // PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
        // dsaKeyPair,
        // userName, sha1Calc, null, null, keySignerBuilder,
        // keyEncryptor);

        // BC
        PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
                dsaKeyPair, userName, sha1CalcBC, null, null, keySignerBuilderBC, keyEncryptorBC);

        keyRingGen.addSubKey(elgKeyPair);
        // building ret
        Key ret = buildKey(keyRingGen);
        return ret;
    } catch (Throwable t) {
        Throwables.propagateIfInstanceOf(t, FieldValidationException.class);
        throw new RuntimeException("Failed to generate key", t);
    }
}

From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java

/**
 *
 *
 * @param clientId//from  w  w  w .  jav a  2  s .c  om
 * @param serverId
 * @param clientKexInit
 * @param serverKexInit
 *
 * @throws IOException
 * @throws AlgorithmOperationException
 * @throws KeyExchangeException
 */
public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit,
        boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch // ignored
) throws IOException {
    log.info("Starting client side key exchange.");
    transport.getMessageStore().registerMessage(SshMsgKexDhInit.SSH_MSG_KEXDH_INIT, SshMsgKexDhInit.class);

    transport.getMessageStore().registerMessage(SshMsgKexDhReply.SSH_MSG_KEXDH_REPLY, SshMsgKexDhReply.class);
    this.clientId = clientId;
    this.serverId = serverId;
    this.clientKexInit = clientKexInit;
    this.serverKexInit = serverKexInit;

    //int minBits = g.bitLength();
    //int maxBits = q.bitLength();
    //Random rnd = ConfigurationLoader.getRND();
    // Generate a random bit count for the random x value

    /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat())
         + minBits);
          x = new BigInteger(genBits, rnd);
          // Calculate e
          e = g.modPow(x, p);*/
    try {
        DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
        dhKeyPairGen.initialize(dhSkipParamSpec);

        KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair();
        dhKeyAgreement.init(dhKeyPair.getPrivate());
        x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX();
        e = ((DHPublicKey) dhKeyPair.getPublic()).getY();
    } catch (InvalidKeyException ex) {
        throw new AlgorithmOperationException("Failed to generate DH value");
    } catch (InvalidAlgorithmParameterException ex) {
        throw new AlgorithmOperationException("Failed to generate DH value");
    }

    // Prepare the message
    SshMsgKexDhInit msg = new SshMsgKexDhInit(e);

    // Send it
    try {
        transport.sendMessage(msg, this);
    } catch (SshException tpe) {
        throw new KeyExchangeException("Failed to send key exchange initailaztion message");
    }

    int[] messageId = new int[1];
    messageId[0] = SshMsgKexDhReply.SSH_MSG_KEXDH_REPLY;

    SshMsgKexDhReply reply = (SshMsgKexDhReply) transport.readMessage(messageId);

    hostKey = reply.getHostKey();
    signature = reply.getSignature();

    f = reply.getF();

    // Calculate diffe hellman k value
    secret = f.modPow(x, p);

    // Calculate the exchange hash
    calculateExchangeHash();
}

From source file:com.sshtools.j2ssh.transport.kex.GssGroup1Sha1.java

/**
 *
 *
 * @param clientId//from www  .  j  a  va 2 s  .com
 * @param serverId
 * @param clientKexInit
 * @param serverKexInit
 *
 * @throws IOException
 * @throws AlgorithmOperationException
 * @throws KeyExchangeException
 */
public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit,
        boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch) throws IOException {
    try {
        log.info("Starting client side key exchange.");
        transport.getMessageStore().registerMessage(SshMsgKexGssInit.SSH_MSG_KEXGSS_INIT,
                SshMsgKexGssInit.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE,
                SshMsgKexGssContinue.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE,
                SshMsgKexGssComplete.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY,
                SshMsgKexGssHostKey.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR,
                SshMsgKexGssError.class);
        this.clientId = clientId;
        this.serverId = serverId;
        this.clientKexInit = clientKexInit;
        this.serverKexInit = serverKexInit;

        //int minBits = g.bitLength();
        //int maxBits = q.bitLength();
        //Random rnd = ConfigurationLoader.getRND();
        // Generate a random bit count for the random x value

        /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat())
         + minBits);
              x = new BigInteger(genBits, rnd);
              // Calculate e
              e = g.modPow(x, p);*/
        try {
            DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
            dhKeyPairGen.initialize(dhSkipParamSpec);

            KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair();
            dhKeyAgreement.init(dhKeyPair.getPrivate());
            x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX();
            e = ((DHPublicKey) dhKeyPair.getPublic()).getY();
        } catch (InvalidKeyException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        } catch (InvalidAlgorithmParameterException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        }
        //C calls GSS_Init_sec_context!
        log.info("Generating shared context with server...");
        GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl();

        HostAuthorization gssAuth = new HostAuthorization(null);
        GSSName targetName = gssAuth.getExpectedName(null, hostname);
        GSSCredential gsscredential = null;
        GSSContext gsscontext = null;
        if (theCredential == null) {
            gsscredential = UserGridCredential.getUserCredential(properties);
            theCredential = gsscredential;
        } else {
            gsscredential = theCredential;
            try {
                ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential().verify();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (GlobusCredentialException e) {
                e.printStackTrace();
                javax.swing.JOptionPane.showMessageDialog(properties.getWindow(),
                        "The credentials that you authenticated with have expired, please re-authenticate.",
                        "GSI-SSH Terminal", javax.swing.JOptionPane.WARNING_MESSAGE);
                gsscredential = UserGridCredential.getUserCredential(properties);
                theCredential = gsscredential;
            }
        }
        gsscontext = globusgssmanagerimpl.createContext(targetName, GSSConstants.MECH_OID, gsscredential,
                GSSCredential.DEFAULT_LIFETIME);

        gsscontext.requestCredDeleg(true);
        gsscontext.requestMutualAuth(true);
        gsscontext.requestInteg(true);
        //gsscontext.requestAnonymity(false);
        // gsscontext.requestReplayDet(false);
        //gsscontext.requestSequenceDet(false);
        // gsscontext.requestConf(false);
        Object type = GSIConstants.DELEGATION_TYPE_LIMITED;
        String cur = "None";
        if (properties instanceof SshToolsConnectionProfile) {
            cur = ((SshToolsConnectionProfile) properties)
                    .getApplicationProperty(SshTerminalPanel.PREF_DELEGATION_TYPE, "Full");
            if (cur.equals("full")) {
                type = GSIConstants.DELEGATION_TYPE_FULL;
            } else if (cur.equals("limited")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
            } else if (cur.equals("none")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
                gsscontext.requestCredDeleg(false);
            }
        }
        log.debug("Enabling delegation setting: " + cur);
        ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type);

        log.debug("Starting GSS token exchange.");
        byte abyte2[] = new byte[0];
        Object obj = null;
        boolean firsttime = true;
        hostKey = null;
        do {
            if (gsscontext.isEstablished())
                break;
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
            if (abyte3 != null) {
                if (firsttime) {
                    SshMsgKexGssInit msg = new SshMsgKexGssInit(e, /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                } else {
                    SshMsgKexGssContinue msg = new SshMsgKexGssContinue(
                            /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                }
            } else {
                throw new KeyExchangeException("Expecting a non-zero length token from GSS_Init_sec_context.");
            }
            if (!gsscontext.isEstablished()) {
                int[] messageId = new int[3];
                messageId[0] = SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY;
                messageId[1] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                messageId[2] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                SshMessage msg = transport.readMessage(messageId);
                if (msg.getMessageId() == SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY) {
                    if (!firsttime) {
                        throw new KeyExchangeException(
                                "Not expecting a SSH_MSG_KEXGS_HOSTKEY message at this time.");
                    }
                    SshMsgKexGssHostKey reply = (SshMsgKexGssHostKey) msg;
                    hostKey = reply.getHostKey();
                    messageId = new int[2];
                    messageId[0] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                    messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                    msg = transport.readMessage(messageId);
                    if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
                        errormsg(msg);
                } else if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) {
                    errormsg(msg);
                }
                SshMsgKexGssContinue reply = (SshMsgKexGssContinue) msg;
                abyte2 = reply.getToken();
            }
            firsttime = false;
        } while (true);
        log.debug("Sending gssapi exchange complete.");
        int[] messageId = new int[2];
        messageId[0] = SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE;
        messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
        SshMessage msg = transport.readMessage(messageId);
        if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
            errormsg(msg);
        SshMsgKexGssComplete reply = (SshMsgKexGssComplete) msg;
        if (reply.hasToken()) {
            ByteArrayReader bytearrayreader1 = new ByteArrayReader(reply.getToken());
            abyte2 = bytearrayreader1.readBinaryString();
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (abyte3 != null) {
                throw new KeyExchangeException("Expecting zero length token.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
        }

        byte per_msg_token[] = reply.getMIC();
        f = reply.getF();

        // Calculate diffe hellman k value
        secret = f.modPow(x, p);

        // Calculate the exchange hash
        calculateExchangeHash();

        gsscontext.verifyMIC(per_msg_token, 0, per_msg_token.length, exchangeHash, 0, exchangeHash.length,
                null);

        gssContext = gsscontext;
    } catch (GSSException g) {
        String desc = g.toString();
        if (desc.startsWith(
                "GSSException: Failure unspecified at GSS-API level (Mechanism level: GSS Major Status: Authentication Failed")
                && desc.indexOf("an unknown error occurred") >= 0) {
            throw new KeyExchangeException(
                    "Error from GSS layer: \n Probably due to your proxy credential being expired or signed by a CA unknown by the server or your clock being set wrong.",
                    g);
        } else {
            if (desc.indexOf("From Server") >= 0) {
                throw new KeyExchangeException("GSS Error from server", g);
            } else {
                throw new KeyExchangeException("Error from GSS layer", g);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}