0

嗨,我正在尝试按照本教程中的本教程实现 OAuth1.0,有一个标题 OAuthGetRequestToken

为了获取请求令牌,我们必须向 URL 发送一个 post 请求

www.google.com/accounts/OAuthGetRequestToken

我在谷歌应用引擎的代码中发送一个发布请求我的代码是:

public class HelloWorldServlet extends HttpServlet {
    @SuppressWarnings({ "unchecked", "unchecked" })
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {



        resp.setContentType("text/html");
         resp.getWriter().println("<html><head> <meta name=\"google-site-verification\" content=\"OBFeK6hFEbTkNdcYc-SQNH9tCTpcht-HkUdj6IgCaLg\" </head>");

        resp.getWriter().println("<body>Hello, world");
        //String post="key=AIzaSyBgmwbZaW3-1uaVOQ9UqlyHAUxvQtHe7X0&oauth_consumer_key=iriteshmehandiratta.appspot.com";
        //String param= "&oauth_callback=\"https://www.iriteshmehandiratta.appspot.com\"&scope=\"http://www.google.com/calendar/feeds\""; 


        //URL url=new URL("https://www.googleapis.com/prediction/v1.5/trainedmodels/10/predict?");
  TreeMap<String,String> tree=new TreeMap<String,String>();
  tree.put("oauth_version","1.0");
  tree.put("oauth_nonce", System.currentTimeMillis()+"");
  tree.put("oauth_timestamp",System.currentTimeMillis()/1000+"");
  tree.put("oauth_consumer_key", "imehandirattaritesh.appspot.com");
  tree.put("oauth_signature_method", "RSA-SHA1");

  ServletContext context = getServletContext();
  PrivateKey privKey = getPrivateKey(context,"/myrsakey11.pk8");




  tree.put("oauth_callback", "https://imehandirattaritesh.appspot.com/authsub");
  tree.put("scope", "https://www.google.com/calendar/feeds");
  Set set = tree.entrySet(); 

  Iterator<Map.Entry<String, String>> i = set.iterator(); 
  String datastring="";
  Map.Entry me=(Map.Entry)i.next();
 datastring=me.getKey()+"=";
 datastring+=me.getValue();

 while(i.hasNext()) { 
      me = (Map.Entry)i.next(); 
      datastring+="&"+me.getKey()+"="; 
      datastring+=(me.getValue()); 
      } 
  String data_string="GET&https://www.google.com/accounts/OAuthGetRequestToken&"+datastring;
 byte[] xx11;
 String str = null;
try {
    xx11 = sign(privKey,data_string);
    str=new String(xx11);
resp.getWriter().println(str);

} catch (GeneralSecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}



URL url=new URL("https://www.google.com/accounts/OAuthGetRequestToken?"+str); 
            //  resp.getWriter().println(""+datastring);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        urlConnection.setRequestProperty("Authorization", " OAuth");

        urlConnection.setRequestMethod("GET");

        urlConnection.setDoOutput(true);

        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

          resp.getWriter().println( urlConnection.getResponseCode());

           String xx="";

           String xx1="";

           while((xx1=in.readLine()) != null)

           {
               xx+=xx1;


           }
           resp.getWriter().println("response");
           resp.getWriter().println(xx);
           resp.getWriter().println("</body></html>");




    }


    public static PrivateKey getPrivateKey(ServletContext context,String privKeyFileName) throws IOException {

        InputStream resourceContent = context.getResourceAsStream("/WEB-INF/myrsakey11.pk8");
         // FileInputStream fis = new FileInputStream(privKeyFile);
          DataInputStream dis  = new DataInputStream(resourceContent);

          @SuppressWarnings("deprecation")
        String str="";
          String str1="";
          while((str=dis.readLine())!=null)
          {
              str1+=str;

          }



          String BEGIN = "-----BEGIN PRIVATE KEY-----";
          String END = "-----END PRIVATE KEY-----";
         // String str = new String(privKeyBytes);

          if (str1.contains(BEGIN) && str1.contains(END)) {
            str1 = str1.substring(BEGIN.length(), str1.lastIndexOf(END));
          }

          KeyFactory fac;
        try {
            fac = KeyFactory.getInstance("RSA");

              EncodedKeySpec privKeySpec= new PKCS8EncodedKeySpec(Base64.decode(str1));
              return fac.generatePrivate(privKeySpec);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Base64DecoderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         return null;

          }


    byte[] sign(PrivateKey key, String data) throws GeneralSecurityException {
        Signature signature = Signature.getInstance("SHA1withRSA"); 
        signature.initSign(key);

        signature.update(data.getBytes());
        return signature.sign(); 
        }
}

首先我生成 data_string 然后使用我的私钥对其进行签名我得到一个像这样的加密字符串

 F????T???&??$????????l:v????x???}??U-'?"?????U?[?kr^?G?(? ???qT0??]??j???5??`??$??AD??T??@<t?,#:`V????????????

然后我将它与 url 连接起来:https://www.google.com/accounts/OAuthGetRequestToken?我收到 400 错误,显然它不是有效的 uri 格式,所以我收到此错误。我在 stackoverflow 上发布了一个查询,有人建议我使用 sign 方法,在签署 data_string 后,我将在返回字符串中嵌入 oauth_signature,该字符串是变量 str但是代替oauth_signature,我得到了一个加密字符串,谁能告诉我如何签署这个data_string以及我在做什么错误?

4

1 回答 1

0

我建议您使用现有的 Java 库来执行 OAuth。从长远来看,这会容易得多,您不必担心调试协议。

于 2013-01-11T16:38:32.190 回答