KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > socks > UserPasswordAuthentication


1 package socks;
2
3 /**
4   SOCKS5 User Password authentication scheme.
5 */

6 public class UserPasswordAuthentication implements Authentication{
7
8    /**SOCKS ID for User/Password authentication method*/
9    public final static int METHOD_ID = 2;
10
11    String JavaDoc userName, password;
12    byte[] request;
13
14    /**
15      Create an instance of UserPasswordAuthentication.
16      @param userName User Name to send to SOCKS server.
17      @param password Password to send to SOCKS server.
18    */

19    public UserPasswordAuthentication(String JavaDoc userName,String JavaDoc password){
20      this.userName = userName;
21      this.password = password;
22      formRequest();
23    }
24    /** Get the user name.
25    @return User name.
26    */

27    public String JavaDoc getUser(){
28      return userName;
29    }
30    /** Get password
31    @return Password
32    */

33    public String JavaDoc getPassword(){
34      return password;
35    }
36    /**
37     Does User/Password authentication as defined in rfc1929.
38     @return An array containnig in, out streams, or null if authentication
39     fails.
40    */

41    public Object JavaDoc[] doSocksAuthentication(int methodId,
42                                          java.net.Socket JavaDoc proxySocket)
43                    throws java.io.IOException JavaDoc{
44
45       if(methodId != METHOD_ID) return null;
46
47       java.io.InputStream JavaDoc in = proxySocket.getInputStream();
48       java.io.OutputStream JavaDoc out = proxySocket.getOutputStream();
49
50       out.write(request);
51       int version = in.read();
52       if(version < 0) return null; //Server closed connection
53
int status = in.read();
54       if(status != 0) return null; //Server closed connection, or auth failed.
55

56       return new Object JavaDoc[] {in,out};
57    }
58
59 //Private methods
60
//////////////////
61

62 /** Convert UserName password in to binary form, ready to be send to server*/
63    private void formRequest(){
64       byte[] user_bytes = userName.getBytes();
65       byte[] password_bytes = password.getBytes();
66
67       request = new byte[3+user_bytes.length+password_bytes.length];
68       request[0] = (byte) 1;
69       request[1] = (byte) user_bytes.length;
70       System.arraycopy(user_bytes,0,request,2,user_bytes.length);
71       request[2+user_bytes.length] = (byte) password_bytes.length;
72       System.arraycopy(password_bytes,0,
73                        request,3+user_bytes.length,password_bytes.length);
74    }
75 }
76
Popular Tags