⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 srpclient.java

📁 linux下建立JAVA虚拟机的源码KAFFE
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* SRPClient.java --    Copyright (C) 2003, 2006 Free Software Foundation, Inc.This file is a part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or (atyour option) any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301USALinking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version.  */package gnu.javax.crypto.sasl.srp;import gnu.java.security.Registry;import gnu.java.security.hash.MD5;import gnu.java.security.util.PRNG;import gnu.java.security.util.Util;import gnu.javax.crypto.key.IKeyAgreementParty;import gnu.javax.crypto.key.IncomingMessage;import gnu.javax.crypto.key.KeyAgreementFactory;import gnu.javax.crypto.key.KeyAgreementException;import gnu.javax.crypto.key.OutgoingMessage;import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;import gnu.javax.crypto.assembly.Direction;import gnu.javax.crypto.cipher.CipherFactory;import gnu.javax.crypto.cipher.IBlockCipher;import gnu.javax.crypto.sasl.ClientMechanism;import gnu.javax.crypto.sasl.IllegalMechanismStateException;import gnu.javax.crypto.sasl.InputBuffer;import gnu.javax.crypto.sasl.IntegrityException;import gnu.javax.crypto.sasl.OutputBuffer;import gnu.javax.security.auth.Password;import java.io.IOException;import java.io.PrintWriter;import java.io.ByteArrayOutputStream;import java.io.UnsupportedEncodingException;import java.math.BigInteger;import java.security.NoSuchAlgorithmException;import java.util.Arrays;import java.util.HashMap;import java.util.StringTokenizer;import javax.security.auth.callback.Callback;import javax.security.auth.callback.NameCallback;import javax.security.auth.callback.PasswordCallback;import javax.security.auth.callback.UnsupportedCallbackException;import javax.security.auth.DestroyFailedException;import javax.security.sasl.AuthenticationException;import javax.security.sasl.SaslClient;import javax.security.sasl.SaslException;/** * <p>The SASL-SRP client-side mechanism.</p> */public class SRPClient extends ClientMechanism implements SaslClient{  // Debugging methods and variables  // -------------------------------------------------------------------------  private static final String NAME = "SRPClient";  //   private static final String ERROR = "ERROR";  //   private static final String WARN =  " WARN";  private static final String INFO = " INFO";  private static final String TRACE = "DEBUG";  private static final boolean DEBUG = true;  private static final int debuglevel = 3;  private static final PrintWriter err = new PrintWriter(System.out, true);  private static void debug(final String level, final Object obj)  {    err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));  }  // Constants and variables  // -------------------------------------------------------------------------  //   private static final HashMap uid2ctx = new HashMap();  private String uid; // the unique key for this type of client  private String U; // the authentication identity  BigInteger N, g, A, B;  private Password password; // the authentication credentials  private byte[] s; // the user's salt  private byte[] cIV, sIV; // client+server IVs, when confidentiality is on  private byte[] M1, M2; // client+server evidences  private byte[] cn, sn; // client's and server's nonce  private SRP srp; // SRP algorithm instance used by this client  private byte[] sid; // session ID when re-used  private int ttl; // session time-to-live in seconds  private byte[] sCB; // the peer's channel binding data  private String L; // available options  private String o;  private String chosenIntegrityAlgorithm;  private String chosenConfidentialityAlgorithm;  private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;  private byte[] K; // shared session key  private boolean replayDetection = true; // whether Replay Detection is on  private int inCounter = 0; // messages sequence numbers  private int outCounter = 0;  private IALG inMac, outMac; // if !null, use for integrity  private CALG inCipher, outCipher; // if !null, use for confidentiality  private IKeyAgreementParty clientHandler = KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA);  /** Our default source of randomness. */  private PRNG prng = null;  // Constructor(s)  // -------------------------------------------------------------------------  public SRPClient()  {    super(Registry.SASL_SRP_MECHANISM);  }  // Class methods  // -------------------------------------------------------------------------  // Instance methods  // -------------------------------------------------------------------------  // abstract methods implementation -----------------------------------------  protected void initMechanism() throws SaslException  {    // we shall keep track of the sid (and the security context of this    // SRP client) based on the initialisation parameters of an SRP session.    // we shall compute a unique key for those parameters and key the sid    // (and the security context) accordingly.    // 1. compute the mapping key. use MD5 (the fastest) for this purpose    final MD5 md = new MD5();    byte[] b;    b = authorizationID.getBytes();    md.update(b, 0, b.length);    b = serverName.getBytes();    md.update(b, 0, b.length);    b = protocol.getBytes();    md.update(b, 0, b.length);    if (channelBinding.length > 0)      {        md.update(channelBinding, 0, channelBinding.length);      }    uid = Util.toBase64(md.digest());    if (ClientStore.instance().isAlive(uid))      {        final SecurityContext ctx = ClientStore.instance().restoreSession(uid);        srp = SRP.instance(ctx.getMdName());        sid = ctx.getSID();        K = ctx.getK();        cIV = ctx.getClientIV();        sIV = ctx.getServerIV();        replayDetection = ctx.hasReplayDetection();        inCounter = ctx.getInCounter();        outCounter = ctx.getOutCounter();        inMac = ctx.getInMac();        outMac = ctx.getOutMac();        inCipher = ctx.getInCipher();        outCipher = ctx.getOutCipher();      }    else      {        sid = new byte[0];        ttl = 0;        K = null;        cIV = null;        sIV = null;        cn = null;        sn = null;      }  }  protected void resetMechanism() throws SaslException  {    try      {        password.destroy();      }    catch (DestroyFailedException dfe)      {        SaslException se = new SaslException("resetMechanism()");        se.initCause(dfe);        throw se;      }    password = null;    M1 = null;    K = null;    cIV = null;    sIV = null;    inMac = outMac = null;    inCipher = outCipher = null;    sid = null;    ttl = 0;    cn = null;    sn = null;  }  // javax.security.sasl.SaslClient interface implementation -----------------  public boolean hasInitialResponse()  {    return true;  }  public byte[] evaluateChallenge(final byte[] challenge) throws SaslException  {    switch (state)      {      case 0:        state++;        return sendIdentities();      case 1:        state++;        final byte[] result = sendPublicKey(challenge);        try          {            password.destroy(); //don't need further this session          }        catch (DestroyFailedException x)          {            SaslException se = new SaslException("sendPublicKey()");            se.initCause(se);            throw se;          }        return result;      case 2: // should only occur if session re-use was rejected        if (!complete)          {            state++;            return receiveEvidence(challenge);          }      // else fall through      default:        throw new IllegalMechanismStateException("evaluateChallenge()");      }  }  protected byte[] engineUnwrap(final byte[] incoming, final int offset,                                final int len) throws SaslException  {    if (DEBUG && debuglevel > 8)      debug(TRACE, "==> engineUnwrap()");    if (inMac == null && inCipher == null)      {        throw new IllegalStateException("connection is not protected");      }    // at this point one, or both, of confidentiality and integrity protection    // services are active.    final byte[] result;    try      {        //         final InputBuffer frameIn = InputBuffer.getInstance(incoming, offset, len);        //         result = frameIn.getEOS();        if (inMac != null)          { // integrity bytes are at the end of the stream            final int macBytesCount = inMac.length();            final int payloadLength = len - macBytesCount;            //            final byte[] received_mac = frameIn.getOS();            final byte[] received_mac = new byte[macBytesCount];            System.arraycopy(incoming, offset + payloadLength, received_mac, 0,                             macBytesCount);            if (DEBUG && debuglevel > 6)              debug(TRACE, "Got C (received MAC): "                           + Util.dumpString(received_mac));            //            inMac.update(result);            inMac.update(incoming, offset, payloadLength);            if (replayDetection)              {                inCounter++;                if (DEBUG && debuglevel > 6)                  debug(TRACE, "inCounter=" + String.valueOf(inCounter));                inMac.update(new byte[] { (byte) (inCounter >>> 24),                                         (byte) (inCounter >>> 16),                                         (byte) (inCounter >>> 8),                                         (byte) inCounter });              }            final byte[] computed_mac = inMac.doFinal();            if (DEBUG && debuglevel > 6)              debug(TRACE, "Computed MAC: " + Util.dumpString(computed_mac));            if (!Arrays.equals(received_mac, computed_mac))              {                throw new IntegrityException("engineUnwrap()");              }            // deal with the payload, which can be either plain or encrypted            if (inCipher != null)              {                result = inCipher.doFinal(incoming, offset, payloadLength);              }            else              {                result = new byte[len - macBytesCount];                System.arraycopy(incoming, offset, result, 0, result.length);              }          }        else          { // no integrity protection; just confidentiality          //            if (inCipher != null) {            result = inCipher.doFinal(incoming, offset, len);            //            } else {            //               result = new byte[len];            //               System.arraycopy(incoming, offset, result, 0, len);            //            }          }        //         if (inCipher != null) {        //            result = inCipher.doFinal(result);        //         }      }    catch (IOException x)      {        if (x instanceof SaslException)          {            throw (SaslException) x;          }        throw new SaslException("engineUnwrap()", x);      }    if (DEBUG && debuglevel > 8)      debug(TRACE, "<== engineUnwrap()");    return result;  }  protected byte[] engineWrap(final byte[] outgoing, final int offset,                              final int len) throws SaslException  {    if (DEBUG && debuglevel > 8)      debug(TRACE, "==> engineWrap()");    if (outMac == null && outCipher == null)      {        throw new IllegalStateException("connection is not protected");      }    // at this point one, or both, of confidentiality and integrity protection    // services are active.    //      byte[] data = new byte[len];    //      System.arraycopy(outgoing, offset, data, 0, len);    byte[] result;    try      {        //         OutputBuffer frameOut = new OutputBuffer();

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -