JAVA代码转C#,请高手帮忙看看

LostAngel911 2012-09-04 09:39:46
在做新浪最新的模拟登录,找了一段代码是JAVA的。。。实在搞不定。。不知道没有高手在。能不能帮忙转一下
代码如下:

package cn.zju.topicproject.crawler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import cn.zju.topicproject.utility.Configuration;

public class CrawlerLoginUtility {
private final static DefaultHttpClient client = HttpsClient.getInstance();
private static Logger log = Logger.getLogger(CrawlerLoginUtility.class);

public boolean doLogin() {
String usernameBase64 = null;
String username = Configuration.getProperty("managername");
String pwd = Configuration.getProperty("managerpassword");
String clientId = Configuration.getProperty("clientid");
String redirectURI = Configuration.getProperty("redirectURI");

usernameBase64 = SinaEncoder.encodeAccount(username);

String location = null;

try {
// 如果获得location失败,重复登录5次
for (int i = 0; i < 5; i++) {
// 获得公钥
HashMap<String, String> hm = preLogin(usernameBase64);
// 利用公钥将密码加密
String sp = SinaEncoder.RSAEncrypt(pwd, hm.get("pubkey"),
"10001");
// 将加密之后的密码传入,进行登录,获得ticket
hm = login(hm, usernameBase64, sp);
location = authorize(hm.get("ticket"), redirectURI, clientId,
username);
System.out.println("location: "+location);
if (location == null)
continue;
else
get(location);
return true;
}
} catch (Exception e) {
log.error(e.getMessage());
}

return false;
}

/**
* 根据URL,get网页
*
* @param url
* @throws IOException
*/
private String get(String url) throws IOException {
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
String result = dump(entity);
get.abort();
return result;
}

/**
* 新浪微博预登录,获取密码加密公钥
*
* @param unameBase64
* @return 返回从结果获取的参数的哈希表
* @throws IOException
*/
private HashMap<String, String> preLogin(String unameBase64)
throws IOException {
String url = "https://login.sina.com.cn/sso/prelogin.php?"
+ "entry=openapi&"
+ "callback=sinaSSOController.preloginCallBack&" + "su="
+ unameBase64 + "&" + "rsakt=mod&"
+ "client=ssologin.js(v1.4.1)";
return getParaFromResult(get(url));
}

/**
* 登录,获得授权过程的需要的ticket
*
* @param para
* 从prelogin中获得的参数哈希表
* @param usernameBase64
* @param sp
* 经过RSA加密后的密码
* @return
* @throws Exception
*/
private HashMap<String, String> login(HashMap<String, String> para,
String usernameBase64, String sp) throws Exception {
String url = "https://login.sina.com.cn/sso/login.php?"
+ "entry=openapi&" + "gateway=1&" + "from=&" + "savestate=0&"
+ "useticket=1&" + "ct=1800&" + "s=1&" + "vsnf=1&" + "vsnval=&"
+ "door=&" + "su="
+ usernameBase64
+ "&"
+ "service=miniblog&"
+ "servertime="
+ para.get("servertime")
+ "&"
+ "nonce="
+ para.get("nonce")
+ "&"
+ "pwencode=rsa&"
+ "rsakv="
+ para.get("rsakv")
+ "&"
+ "sp="
+ sp
+ "&"
+ "encoding=UTF-8&"
+ "callback=sinaSSOController.loginCallBack&"
+ "cdult=2&"
+ "domain=weibo.com&"
+ "prelt=186&"
+ "returntype=TEXT&"
+ "client=ssologin.js(v1.4.1)&" + "_=" + new Date().getTime();

return getParaFromResult(get(url));
}

/**
* 执行登录过程
*
* @param user
* @param pwd
* @param debug
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private String authorize(String ticket, String redirectURI,
String clientId, String username) throws IOException,
KeyManagementException, NoSuchAlgorithmException {
HttpPost post = new HttpPost("https://api.weibo.com/oauth2/authorize");
// post.setHeader("Accept",
// "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// post.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
// post.setHeader("Accept-Encoding", "gzip,deflate,sdch");
// post.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
// post.setHeader("Cache-Control", "max-age=0");
// post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Host", "api.weibo.com");
post.setHeader("Origin", "https://api.weibo.com");
post.setHeader(
"Referer",
"https://api.weibo.com/oauth2/authorize?client_id=940301381&redirect_uri=http://db.zju.edu.cn/topiccrowdsourcing/servlet/LoginAuth&response_type=code&forcelogin=true");
// post.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 QIHU 360EE");

// 登录表单的信息
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("action", "submit"));
// qparams.add(new BasicNameValuePair("withOfficalFlag", "0"));
qparams.add(new BasicNameValuePair("ticket", ticket));
// qparams.add(new BasicNameValuePair("isLoginSina", ""));
qparams.add(new BasicNameValuePair("response_type", "code"));
// qparams.add(new BasicNameValuePair("regCallback", ""));
qparams.add(new BasicNameValuePair("redirect_uri", redirectURI));
qparams.add(new BasicNameValuePair("client_id", clientId));
// qparams.add(new BasicNameValuePair("state", ""));
// qparams.add(new BasicNameValuePair("from", ""));
qparams.add(new BasicNameValuePair("userId", username));
// qparams.add(new BasicNameValuePair("passwd", ""));

post.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
HttpResponse response = client.execute(post);
post.abort();
Header LocationHeader = response.getFirstHeader("Location");

return LocationHeader == null ? null : LocationHeader.getValue();

}

/**
* 打印页面
*
* @param entity
* @throws IOException
*/
private String dump(HttpEntity entity) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent(), "utf8"));
return IOUtils.toString(br);
}

/**
* 从新浪返回的结果字符串中获得参数
*
* @param result
* @return
*/
private HashMap<String, String> getParaFromResult(String result) {
HashMap<String, String> hm = new HashMap<String, String>();
result = result.substring(result.indexOf("{") + 1, result.indexOf("}"));
String[] r = result.split(",");
String[] temp;
for (int i = 0; i < r.length; i++) {
temp = r[i].split(":");
for (int j = 0; j < 2; j++) {
if (temp[j].contains("\""))
temp[j] = temp[j].substring(1, temp[j].length() - 1);
}
hm.put(temp[0], temp[1]);
}
return hm;
}
}


package cn.zju.topicproject.crawler;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

public class HttpsClient {
private static Logger log = Logger.getLogger(HttpsClient.class);
private static X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
};

@SuppressWarnings("deprecation")
public static DefaultHttpClient getInstance() {
DefaultHttpClient client = new DefaultHttpClient();
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
client = new DefaultHttpClient(ccm, client.getParams());
}catch(Exception e){
log.error(e.getMessage());
}
return client;
}
}
...全文
369 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dynamic 2014-10-16
  • 打赏
  • 举报
回复
RSA公钥解密
LostAngel911 2012-09-05
  • 打赏
  • 举报
回复
up..n有人看看吗
LostAngel911 2012-09-05
  • 打赏
  • 举报
回复
有人帮看看嘛?
LostAngel911 2012-09-04
  • 打赏
  • 举报
回复
还有一段,发不下的
特别是这段加密的。

package cn.zju.topicproject.crawler;

import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.Random;

import org.apache.commons.codec.binary.Base64;

public class SinaEncoder {
private static BigInteger n = null;
private static BigInteger e = null;

private static BigInteger pkcs1pad2(String s, int n){
if(n < s.length() + 11) { // TODO: fix for utf-8
System.out.println("Message too long for RSA");
return null;
}
byte[] ba = new byte[n];
int i = s.length()-1;
while(i >= 0 && n > 0) {
int c = s.codePointAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = new Byte(String.valueOf(c));
}
else if((c > 127) && (c < 2048)) {
ba[--n] = new Byte(String.valueOf((c & 63) | 128));
ba[--n] = new Byte(String.valueOf((c >> 6) | 192));
}
else {
ba[--n] = new Byte(String.valueOf((c & 63) | 128));
ba[--n] = new Byte(String.valueOf(((c >> 6) & 63) | 128));
ba[--n] = new Byte(String.valueOf((c >> 12) | 224));
}
}
ba[--n] = new Byte("0");

byte[] temp = new byte[1];
Random rdm = new Random(47L);

while(n > 2) { // random non-zero pad
temp[0] = new Byte("0");
while(temp[0] == 0)
rdm.nextBytes(temp);
ba[--n] = temp[0];
}
ba[--n] = 2;
ba[--n] = 0;

return new BigInteger(ba);
}

private static BigInteger RSADoPublic(BigInteger x){
return x.modPow(e, n);
}

@SuppressWarnings("deprecation")
public static String encodeAccount(String account){

return Base64.encodeBase64String(URLEncoder.encode(account).getBytes());
}

public static String RSAEncrypt(String pwd, String nStr, String eStr){
n = new BigInteger(nStr,16);
e = new BigInteger(eStr,16);

BigInteger r = RSADoPublic(pkcs1pad2(pwd,(n.bitLength()+7)>>3));
String sp = r.toString(16);
if((sp.length()&1) != 0 )
sp = "0" + sp;
return sp;
}
}

58,452

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧