Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
io.github.uac.sigle.UAC Maven / Gradle / Ivy
package io.github.uac.sigle;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class UAC {
private String server;
private String id;
private String name;
private String roles;
private String hash;
private String account;
private String cellphone;
private String mail;
private String orgId;
private Integer status;//-1 登陆失败 1 登陆成功 0待处理
private String msg;
private boolean logoned;
private static Charset charset;
public boolean login(String account,String password) {
String code =capToken();
account=TOKEN64.encode(account.getBytes());
password=TOKEN64.encode(password.getBytes());
//TOKEN64
String data=serialization(account,
randomString(3),
password,
randomString(4),
code,
"."
);
String loginString = new HTTP().url(server+"?e=user&uas_login="+data)
.get().asString(charset);
SJ sj = new SJ();
sj.fromString(loginString);
Map user =(Map) sj.getRoot();
if(user.get("id")==null) {
status=-1;
msg=(String) user.get("msg");
return false;
}
id=(String) user.get("id");
name=(String) user.get("name");
hash=(String) user.get("hash");
account=(String) user.get("account");
cellphone=(String) user.get("cellphone");
mail=(String) user.get("mail");
orgId=(String) user.get("orgId");
logoned=true;
status=1;
return logoned;
}
public UAC(String server) {
this.server=server;
useCaptcha();
}
public String getTicket() {
if(!logoned||hash==null)return null;
String uid=randomString(16);
StringBuilder sb = new StringBuilder();
sb.append(id).append(uid).append("0");
String s1= sha256(sb.toString());
sb = new StringBuilder();
sb.append(s1).append(hash);
String s2= sha256(sb.toString());
return serialization(id,uid,"0",s2);
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public static Charset getCharset() {
return charset;
}
public static void setCharset(Charset charset) {
UAC.charset = charset;
}
public String getId() {
return id;
}
public String getAccount() {
return account;
}
public Integer getStatus() {
return status;
}
public String getMsg() {
return msg;
}
static {
try {
charset=Charset.forName("utf-8");
}catch(Exception e) {
}
}
public static String sha256(String str) {
MessageDigest digest=null;
try {
digest = MessageDigest.getInstance("SHA-256");
digest.update(str.getBytes());
return toHexString(digest.digest());
} catch (NoSuchAlgorithmException e) {
}
return "";
}
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
public static String toHexString(byte b) {
int u = toUnsigned(b);
return new String(new char[]{
DIGITS[u >>> 4],
DIGITS[u & 0xf]
});
}
public static String toHexString(byte... bytes) {
char[] buffer = new char[bytes.length * 2];
for (int i = 0, j = 0; i < bytes.length; ++i) {
int u = toUnsigned(bytes[i]);
buffer[j++] = DIGITS[u >>> 4];
buffer[j++] = DIGITS[u & 0xf];
}
return new String(buffer);
}
public static String randomString(int len){
char[] cs = new char[len];
for(int i=0;i=len){
System.arraycopy(c, 0, cs, i, len-i);
}else{
System.arraycopy(c, 0, cs, i, c.length);
}
}
return new String(cs);
}
private static char[] random16(){
long v =Double.doubleToLongBits(Math.random());
long v2 =Double.doubleToLongBits(Math.random());
return fillchar(
(byte)(v2 >>> 32),
(byte)(v2 >>> 24),
(byte)(v >>> 40),
(byte)(v >>> 32),
(byte)(v >>> 24),
(byte)(v >>> 16),
(byte)(v >>> 8),
(byte)(v >>> 0)
);
}
private static char[] fillchar(byte ...v){
char[] cs = new char[v.length*2];
int j=0;
for(int i=0;i>>4];
cs[j+1]=hexarra[toUnsigned(v[i])& 0xf];
}
return cs;
}
private static byte[] writeShort(int v) {
byte[] b = new byte[2];
b[0]=(byte)((v >>> 8) & 0xFF);
b[1]=(byte)((v >>> 0) & 0xFF);
return b;
}
static char[] hexarra="0123456789abcdef".toCharArray();
private static char[] len(int i){
if(i<15){
return new char[]{hexarra[i]};
}
byte[]b=writeShort(i);
return new char[]{
'e',
hexarra[toUnsigned(b[0])>>>4],
hexarra[toUnsigned(b[0])& 0xf],
hexarra[toUnsigned(b[1])>>>4],
hexarra[toUnsigned(b[1])& 0xf]
};
}
private static int toUnsigned(byte b) {
return b < 0 ? b + 256 : b;
}
public static String serialization(String ...str){
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
sb.append(hexarra[str.length]);
for(int i=0;i96){len-=87;}else{len-=48;}
int[] lens= new int[len];
int i=1;
String [] strs =new String[len];
for(int j=0;j96?l-87:l-48;
i+=1;
}
lens[j]=l;
}
for(int j=0;j> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append(legalChars[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}
if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 255) << 8);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append("==");
}
return buf.toString();
}
private static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '.':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;
if (i == len)
break;
int tri = (decode(s.charAt(i)) << 18)
+ (decode(s.charAt(i + 1)) << 12)
+ (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));
os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);
i += 4;
}
}
static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
class NullHostNameVerifier implements HostnameVerifier {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
}
class HTTP {
private String url;
public HTTP(String url) {
this.url=url;
}
public HTTP() {}
public HTTP url(String url) {
this.url=url;
return this;
}
public HTTP get() {
try {
StringBuilder sb = new StringBuilder();
if(param!=null&¶m.size()>0) {
boolean isFirst=true;
for(Entry e : param.entrySet()) {
if(isFirst) {isFirst=false;}else {sb.append("&");}
sb.append(e.getKey()).append("=").append(e.getValue());
}
if(url.indexOf('?')>-1) {
url+="&"+sb;
}else {
url+="?"+sb;
}
}
open("GET");
conn.setDoOutput(false);
} catch (Exception e) {
error=true;
errMsg="can not access :"+url+" msg:"+e.getMessage();
e.printStackTrace();
}
return this;
}
public HTTP post() {
post(param);
return this;
}
public HTTP post(File o) {
return this;
}
public HTTP post(Object o) {
if(o!=null)
post(asJsonString(o));
return this;
}
public HTTP post(String o) {
if(o!=null)
post(o.getBytes(charset));
return this;
}
OutputStream out;
public HTTP post(byte[] bytes) {
if(bytes!=null)
try {
if(isHTTPS(url)) {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
URL uri =new URL(url);
conn = (HttpURLConnection) uri.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
setHeaders(conn,this.headers);
if(headers==null||!headers.containsKey("Content-Type"))
conn.setRequestProperty("Content-Type","text/json");
conn.connect();
OutputStream out =conn.getOutputStream();
out.write(bytes);
out.close();
int status = conn.getResponseCode();
} catch (Exception e) {
error=true;
errMsg="can not access :"+url+" nmsg:"+e.getMessage();
e.printStackTrace();
}
return this;
}
private void setHeaders(HttpURLConnection conn,Mapheader){
if(header==null)return;
for(Object o: header.entrySet()){
Entry entry =(Entry)o;
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
public HTTP param(Map param) {
return this;
}
public HTTP header(Map param) {
return this;
}
HashMapparam= new HashMap();
public HTTP param(String k,String v) {
param.put(k, v);
return this;
}
HashMapheaders= new HashMap();
public HTTP header(String k ,String v) {
headers.put(k, v);
return this;
}
public String asString() {
return asString(charset);
}
public String asString(Charset charset) {
if(this.error)return "{code:\"-1\",msg:\""+errMsg+"\"}";
return new String(asBytes(),charset);
}
InputStream in;
boolean error=false;
String errMsg="";
public byte[] asBytes() {
try {
in=conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b= new byte[1024];
int len=0;
while((len=in.read(b))>0) {
bos.write(b, 0, len);
}
in.close();
in=null;
if(out!=null) {
out.close();
}
out=null;
byte[] bs =bos.toByteArray();
bos.close();
return bs;
} catch (IOException e) {
error=true;
errMsg=e.getMessage();
e.printStackTrace();
}
return new byte[0];
}
HttpURLConnection conn;
private void open(String method) throws Exception {
URL httpurl=null;
if(isHTTPS(url)) {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
httpurl= new URL(url);
conn = (HttpURLConnection) httpurl.openConnection();
conn.setRequestMethod(method);// POST GET PUT DELETE
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
if(headers!=null&&headers.size()>0) {
for(Entry e : headers.entrySet()) {
conn.setRequestProperty(e.getKey(), e.getValue());
}
}
}
public String getResponseHeader(String k) {
return conn.getHeaderField(k);
}
public boolean isHTTPS(String url) {
if(url.toLowerCase().startsWith("https"))return true;
return false;
}
int connectTimeout=1000;
public HTTP setConnectTimeout(int timeout) {
connectTimeout=timeout;
return this;
}
int readTimeout=6000;
public HTTP setReadTimeout(int timeout) {
readTimeout=timeout;
return this;
}
public HTTP basic(String account,String passwd) {
this.header("authorization","Basic "+encode((account+":"+passwd).getBytes()));
return this;
}
}
class SJ {
Object lv[]=new Object [10];//层级的值
String lk[]=new String [10];//层级名称
int lt[]=new int [10];//层级类型
int maxDeep=10;
public SJ(){}
/**
*
* @param deep 支持最大的层级,默认是10
*/
public SJ(int deep){
lv =new Object [deep];//层级的值
lk =new String [deep];//层级名称
lt =new int [deep];//层级类型
maxDeep=deep;
}
public Object getRoot(){
return lv[0];
}
public void fromString(String str){
int level=0;
int flag=0;
String name=null;
while(flag0){
if(lt[level-1]==0){
((Map)lv[level-1]).put(name, obj);
}else{
((List)lv[level-1]).add(obj);
}
}
}
private void add(int level,List obj,String name){
lv[level]=obj;
lk[level]=name;
lt[level]=1;
if(level>0){
if(lt[level-1]==0){
((Map)lv[level-1]).put(name, obj);
}else{
((List)lv[level-1]).add(obj);
}
}
}
private void add(int level,String obj,String name){
if(level>0){
if(lt[level-1]==0){
((Map)lv[level-1]).put(name, obj);
}else{
((List)lv[level-1]).add(obj);
}
}
}
private int tmp_read_len=0;
private String readString(String str,int off){
tmp_read_len=0;
int i=off;
char stop=' ';
char firstChar=str.charAt(off);
if(firstChar=='"'||firstChar=='\''){
stop=firstChar;
off=i=i+1;
}
char lc=0;//上一个字符
boolean hasReturnWord=false;
for(;i> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append(legalChars[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}
if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 255) << 8);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append("==");
}
return buf.toString();
}
private static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '*':
return 62;
case '.':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
/**
* Decodes the given Base64 encoded String to a new byte array. The byte
* array holding the decoded data is returned.
*/
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
int mod= len%4;
if(mod==3)s+="=";
if(mod==2)s+="==";
len=s.length();
while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;
if (i == len)
break;
int tri = (decode(s.charAt(i)) << 18)
+ (decode(s.charAt(i + 1)) << 12)
+ (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));
os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);
i += 4;
}
}
public static String decodeString(String src) {
String str =new String(decode(src));
return unescape(str);
}
public static String escape(String src) {
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length() * 6);
for (i = 0; i < src.length(); i++) {
j = src.charAt(i);
if (Character.isDigit(j) || Character.isLowerCase(j)
|| Character.isUpperCase(j))
tmp.append(j);
else if (j < 256) {
tmp.append("%");
if (j < 16)
tmp.append("0");
tmp.append(Integer.toString(j, 16));
} else {
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
}
public static String unescape(String src) {
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < src.length()) {
pos = src.indexOf("%", lastPos);
if (pos == lastPos) {
if (src.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(src
.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char) Integer.parseInt(src
.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.append(src.substring(lastPos));
lastPos = src.length();
} else {
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
}
String capHash="";
private String s4() {
return randomString(8);
}
private String capToken() {
String uid=s4();
String h =sha256(uid+capHash);
return serialization(uid,s4(),h);
}
public void useCaptcha() {
String versionString = new HTTP().url(server+"?e=version").get().asString(charset);
SJ sj = new SJ();
sj.fromString(versionString);
Map v =(Map) sj.getRoot();
capHash=(String) v.get("hash");
}
public static void main(String[] agrs) {
UAC uac = new UAC("http://127.0.0.1/uas/server");
uac.useCaptcha();
uac.login("admin", "123456");
System.out.println(uac.name);
System.out.println(uac.getTicket());
if(uac.getStatus()==-1) {
System.err.println(uac.getMsg());
}
}
}