Httpclient login to Sina Weibo (non-SDK)

Source: Internet
Author: User

Source: it male chores

After a week of hard work, I finally pushed the Sina Weibo RSA encrypted login. Please note that httpclient is best to use 4.0, otherwise cookie management is very problematic.

On the subject, Sina Weibo recently updated the SSO login method, and the encryption algorithm changed to RSA to obtain nonce, servertime, and pubkey. RSA encryption is involved here, generally, RSA encryption in Java is performed by reading the public key information from a file or converting the base64-encoded public key information into a key and then encrypting it. However, Sina does not provide base64 encryption, instead, it gave an N (see RSA encryption algorithm, RSA Encryption Algorithm), and I first put the pubkey given by Sina as the base64-encoded public key information, so it was a hard time. Later, let's take a closer look at the RSA encryption algorithm. It seems that the pubkey is not base64 encoded. Someone on the Internet analyzed Sina's SSO. JS, so I also looked at it and finally got some gains. Seeing that he resolved the pubkey into biginteger, it was strange that I thought of the encyclopedia of RSA and found that I was wrong, then find the following method. Use pubkey for encryption.

public String rsaCrypt(String modeHex, String exponentHex, String messageg) throws IllegalBlockSizeException,BadPaddingException, NoSuchAlgorithmException,InvalidKeySpecException, NoSuchPaddingException,InvalidKeyException, UnsupportedEncodingException {KeyFactory factory = KeyFactory.getInstance("RSA");BigInteger m = new BigInteger(modeHex, 16); /* public exponent */BigInteger e = new BigInteger(exponentHex, 16); /* modulus */RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);RSAPublicKey pub = (RSAPublicKey) factory.generatePublic(spec);Cipher enc = Cipher.getInstance("RSA");enc.init(Cipher.ENCRYPT_MODE, pub);byte[] encryptedContentKey = enc.doFinal(messageg.getBytes("GB2312"));return new String(Hex.encodeHex(encryptedContentKey));}

The method is not well known, but it does not affect our learning. Get encrypted, next more hard forced is http-client3 this trust, I see someone on the network out of the Code, refer to get down, but their verification method, parameters are problematic, I have replaced all the replicas by referring to someone written in Ruby (SSO 1.4.2). I will continue to ajaxlogin to get my personal information, however, it is hard to say that it will not work during real login. I suspect it is a cookie problem because I have been warned about Cookie reject because Sina SSO has used some techniques to solve cross-origin problems during login. Okay, so I just copied the cookie domain and changed it to .weibo.com to retcode = 6102 when I finally got the user homepage. I checked the SSO. js code and found that the login was unsuccessful.
, Cookie issues. How can I read and think about it? packet capture, analysis, firebug analysis, and Google countless times. Finally, it was still unsuccessful. Helpless to continue Google, painstaking efforts to live up to the people, and ultimately found this, http-client4 to do, I vaguely remember the official recommendations with hc4, so it was done, actually can get some information on the home page, although it is not HTML, it should be successful. If it is not successful before, you can get the personal homepage to get the login HTML. The following is the main code.

Import Java. io. ioexception; import Java. security. invalidkeyexception; import Java. security. nosuchalgorithmexception; import Java. security. spec. invalidkeyspecexception; import Java. util. arraylist; import Java. util. date; import Java. util. list; import javax. crypto. badpaddingexception; import javax. crypto. illegalblocksizeexception; import javax. crypto. nosuchpaddingexception; import Org. apache. commons. codec. binar Y. base64; import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. httpexception; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. parseexception; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. APAC He. HTTP. client. methods. httppost; import Org. apache. HTTP. client. params. cookiepolicy; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. message. basicnamevaluepair; import Org. apache. HTTP. params. httpconnectionparams; import Org. apache. HTTP. protocol. HTTP; import Org. apache. HTTP. util. entityutils; import Org. JSON. jsonexception; import Org. JSON. jsonobject; public class main {static stri Ng sina_pk = "eb2a38568661887fa180bddb5cabd5f21c7bfd59c090cb2d24" + "allow"; static string username = "username"; static string passwd = "password "; private Static final log logger = logfactory. getlog (main. Class); public static void main (string [] ARGs) throws httpexception, ioexception, jsonexception, invalidkeyexception, illegalblocksizeexception, badpaddingexception, expiration, invalidkeyspecexception, callback {callback client = new callback (); client. getparams (). setparameter ("HTTP. protocol. cookie-Policy ", cookiepolicy. browser_compatibility); client. getpa Rams (). setparameter (httpconnectionparams. connection_timeout, 5000); httppost post = new http post ("http://login.sina.com.cn/sso/login.php? Client = ssologin. JS (v1.4.2) "); prelogininfo info = getpreloginbean (client); long servertime = info. servertime; string nonce = info. nonce; string pwdstring = servertime + "\ t" + nonce + "\ n" + "password"; string sp = new bigintegerrsa (). rsacrypt (sina_pk, "10001", pwdstring); List <namevaluepair> nvps = new arraylist <namevaluepair> (); nvps. add (New basicnamevaluepair ("entry", "Weibo"); nvps. add (New basicnameva Luepair ("Gateway", "1"); nvps. add (New basicnamevaluepair ("from", ""); nvps. add (New basicnamevaluepair ("savestate", "7"); nvps. add (New basicnamevaluepair ("useticket", "1"); nvps. add (New basicnamevaluepair ("ssosimplelogin", "1"); nvps. add (New basicnamevaluepair ("vsnf", "1"); // new namevaluepair ("vsnval", ""), nvps. add (New basicnamevaluepair ("Su", encodeusername (username); nvps. add (New basicnamevalu Epair ("service", "miniblog"); nvps. add (New basicnamevaluepair ("servertime", servertime + ""); nvps. add (New basicnamevaluepair ("nonce", Nonce); nvps. add (New basicnamevaluepair ("pwencode", "rsa2"); nvps. add (New basicnamevaluepair ("rsakv", info. rsakv); nvps. add (New basicnamevaluepair ("SP", SP); nvps. add (New basicnamevaluepair ("encoding", "UTF-8"); nvps. add (New basicnamevaluepair ("prelt", "115"); nvps. Add (New basicnamevaluepair ("returntype", "meta"); nvps. Add (New basicnamevaluepair ("url", "http://weibo.com/ajaxlogin.php? Framelogin = 1 & callback = parent. sinassocontroller. feedbackurlcallback "); Post. setentity (New urlencodedformentity (nvps, HTTP. utf_8); httpresponse response = client.exe cute (post); string entity = entityutils. tostring (response. getentity (); string url = entity. substring (entity. indexof ("http://weibo.com/ajaxlogin.php? "), Entity. indexof ("code = 0") + 6); logger. debug ("url:" + URL); // obtain the actual URL to connect httpget getmethod = new httpget (URL); response = client.exe cute (getmethod); entity = entityutils. tostring (response. getentity (); entity = entity. substring (entity. indexof ("userdomain") + 13, entity. lastindexof ("\" "); logger. debug (entity); getmethod = new httpget ("http://weibo.com/humingchun? WVR = 5 & LF = reg "); response = client.exe cute (getmethod); entity = entityutils. tostring (response. getentity (); // document DOC = // jsoup. parse (entityutils. tostring (response. getentity (); system. out. println (entity); logger. debug (entity);} Private Static prelogininfo getpreloginbean (httpclient client) throws httpexception, ioexception, jsonexception {string servertime = getprelogininfo (client); system. out. Println (""); jsonobject jsoninfo = new jsonobject (servertime); prelogininfo info = new prelogininfo (); info. nonce = jsoninfo. getstring ("nonce"); info. PCID = jsoninfo. getstring ("PCID"); info. pubkey = jsoninfo. getstring ("pubkey"); info. retcode = jsoninfo. getint ("retcode"); info. rsakv = jsoninfo. getstring ("rsakv"); info. servertime = jsoninfo. getlong ("servertime"); Return Info;} public static string getprelogi Ninfo (httpclient client) throws parseexception, ioexception {string preloginurl = "http://login.sina.com.cn/sso/prelogin.php? Entry = SSO & "+" Callback = sinassocontroller. prelogincallback & su = "+" dw5kzwzpbmvk "+" & rsakt = mod & client = ssologin. JS (v1.4.2) "+" & _ = "+ getcurrenttime (); httpget get = new httpget (preloginurl); httpresponse response = client.exe cute (get); string getresp = entityutils. tostring (response. getentity (); int firstleftbracket = getresp. indexof ("("); int lastrightbracket = getresp. lastindexof (")"); string jsonbody = getresp. substring (firstleftbracket + 1, lastrightbracket); system. out. println (jsonbody); Return jsonbody;} Private Static string getcurrenttime () {long servertime = new date (). gettime ()/1000; return string. valueof (servertime);} Private Static string encodeusername (string email) {email = Email. replacefirst ("@", "% 40"); // mzm3mjqwntuyjtqwcxeuy29temail = base64.encodebase64string (email. getbytes (); return email ;}}

Complete source code here to download the http://marspring.mobi/http-client-weibo/ article provides the download link

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.