在android客户端/服务器上实现CHAP

时间:2017-05-31 09:53:38

标签: android authentication client-server

我试图模仿CHAP来验证用户,但不知何故我的哈希在服务器端总是不同的(客户端生成的哈希值和服务器生成的哈希值)。我的代码如下:

服务器端

 public String getMD5Hex(String inputString) throws NoSuchAlgorithmException {

    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(inputString.getBytes());

    byte[] digest = md.digest();

    return digest.toString();
}

public Boolean aliceChapAuth(Socket socket, byte[] sharedKey) {

    Boolean check = false;

    try {
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        //generate challenge
        BigInteger b = new BigInteger(256, new Random());

        //send Challenge
        out.writeObject(b);
        out.flush();

        //receive hash
        String hash = (String)in.readObject();

        //compare foreign and local hash
        String s = sharedKey.toString();

        toastDisplay(getMD5Hex(b+s)+" "+hash);

        if(hash == getMD5Hex(b+s)) {

            check = true;
        }
        //send response


    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return check;
}

N.B toastDisplay()只是我用来烘烤字符串的方法

 public void bobChapAuth(Socket socket, byte[] sharedKey) {

    try {
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        //receive challenge
        BigInteger b = (BigInteger)in.readObject();

        //String s = new String(sharedKey);
        String s = sharedKey.toString();
        //byte[] bytes = example.getBytes();

        //Hash the challenge+sharedSecret
        String hash = getMD5Hex(b+s);

        //send the hash
        out.writeObject(hash);
        out.flush();

        toastDisplay(hash);

        //get final response

    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

从客户端发送的哈希成功接收并且是相同的。

0 个答案:

没有答案