OAuth2 Java Web implementation PKIX error mu edx

Source: Internet
Author: User
Tags sha1


1.

public static void Main (string[] args) {

hostnameverifier HV = new Hostnameverifier () {
public boolean verify (String Urlhostname, sslsession session) {
System.out.println ("Warning:url Host:" + urlhostname + "vs."
+ Session.getpeerhost ());
return true;
}
};

HttpClient client = new Defaulthttpclient ();
HttpPost post = new HttpPost (url+ "/oauth2/access_token");
String tokenstring = client_id+ ":" +client_secret;
String authorization = "Basic" + base64.encodebase64urlsafestring (Tokenstring.getbytes ());
Authorization.replace ("\ n", "");
Post.setheader ("Authorization", Authorization);
list<namevaluepair> params = new arraylist<namevaluepair> ();
Params.add (New Basicnamevaluepair ("Grant_type", "password"));
Params.add (New Basicnamevaluepair ("username", "staff"));
Params.add (New Basicnamevaluepair ("client_id", client_id));
Params.add (New Basicnamevaluepair ("Client_secret", Client_secret));
Params.add (New Basicnamevaluepair ("Password", "[email protected] #wp"));
Params.add (New Basicnamevaluepair ("Client_type", "public"));
Params.add (New Basicnamevaluepair ("Redirect_uri", "http://sinochem.unihse.com"));
Params.add (New Basicnamevaluepair ("ContentType", "Application/x-www-form-urlencoded;charset=utf-8"));

Urlencodedformentity uefentity;
try {
Trustallhttpscertificates ();
Httpsurlconnection.setdefaulthostnameverifier (HV);

uefentity = new Urlencodedformentity (params, "UTF-8");
Post.setentity (uefentity);
HttpResponse response = Client.execute (POST);

String CourseID = "Course-v1:unihse+uni001+2015_t2";
String userName = "Jason";
String Server = "http://sinochem.unihse.com";
String urlnew = server+ "/siteapi/grade/courses/" +courseid+ "/username/" +username;
InputStream is = Response.getentity (). getcontent ();
String SS = Inputstream2string (IS);
Jsonobject JSON = jsonobject.parseobject (ss);
HttpGet post2 = new HttpGet (urlnew);
Post2.setheader ("Authorization", "Bearer" +json.getstring ("Access_token"));
HttpResponse Response2 = Client.execute (POST2);
String s = entityutils.tostring (Response2.getentity (), "UTF-8");

System.out.println ("===================!" +s);
} catch (Exception e) {
E.printstacktrace ();
}
}


2.

Package com.safewaychina.safeye.web.util;

/*
* Copyright 2006 Sun Microsystems, Inc. All rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* Modification, is permitted provided that the following conditions
* is met:
*
*-Redistributions of source code must retain the above copyright
* Notice, this list of conditions and the following disclaimer.
*
*-redistributions in binary form must reproduce the above copyright
* Notice, this list of conditions and the following disclaimer in the
* Documentation and/or other materials provided with the distribution.
*
*-Neither the name of Sun Microsystems nor the names of its
* Contributors May is used to endorse or promote products derived
* From this software without specific prior written permission.
*
* This software are provided by the COPYRIGHT holders and CONTRIBUTORS "as
* is ' and any EXPRESS ' OR implied warranties, including, but not LIMITED to,
* The implied warranties of merchantability and FITNESS for A particular
* PURPOSE is disclaimed. In NO EVENT shall the COPYRIGHT OWNER OR
* CONTRIBUTORS is liable for any DIRECT, INDIRECT, incidental, special,
* Exemplary, OR consequential damages (including, but not LIMITED to,
* Procurement of substitute GOODS OR SERVICES; LOSS of Use, DATA, OR
* PROFITS; OR business interruption) however caused and on any theory of
* Liability, WHETHER in contract, STRICT liability, OR TORT (including
* Negligence OR OTHERWISE) arising in any-out-of-the-
* Software, even IF advised of the possibility of SUCH DAMAGE.
*/

Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.security.KeyStore;
Import Java.security.MessageDigest;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;

Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLException;
Import Javax.net.ssl.SSLSocket;
Import Javax.net.ssl.SSLSocketFactory;
Import Javax.net.ssl.TrustManager;
Import Javax.net.ssl.TrustManagerFactory;
Import Javax.net.ssl.X509TrustManager;

public class Installcert {

public static void Main (string[] args) throws Exception {
String host;
int port;
Char[] Passphrase;
args = new string[]{"Sinochem.unihse.com"};
if ((args.length = = 1) | | (Args.length = = 2)) {
String[] C = Args[0].split (":");
host = C[0];
Port = (C.length = = 1)? 443:integer.parseint (c[1]);
String p = (Args.length = = 1)? "Changeit": args[1];
Passphrase = P.tochararray ();
} else {
System.out
. println ("Usage:java installcert Return
}

File File = new file ("Jssecacerts");
if (file.isfile () = = False) {
char SEP = File.separatorchar;
File dir = new file (System.getproperty ("java.home") + sep+ "JRE" +sep + "Lib"
+ SEP + "security");
File = new file (dir, "jssecacerts");
if (file.isfile () = = False) {
File = new file (dir, "cacerts");
}
}
System.out.println ("Loading KeyStore" + file + "...");
InputStream in = new FileInputStream (file);
KeyStore ks = Keystore.getinstance (Keystore.getdefaulttype ());
Ks.load (in, passphrase);
In.close ();

Sslcontext context = sslcontext.getinstance ("TLS");
Trustmanagerfactory TMF = trustmanagerfactory
. getinstance (Trustmanagerfactory.getdefaultalgorithm ());
Tmf.init (KS);
X509trustmanager Defaulttrustmanager = (x509trustmanager) TMF
. Gettrustmanagers () [0];
Savingtrustmanager TM = new Savingtrustmanager (Defaulttrustmanager);
Context.init (NULL, new trustmanager[] {TM}, NULL);
Sslsocketfactory factory = Context.getsocketfactory ();

System.out
. println ("Opening connection to" + Host + ":" + Port + "...");
Sslsocket socket = (sslsocket) factory.createsocket (host, Port);
Socket.setsotimeout (10000);
try {
System.out.println ("Starting SSL handshake ...");
Socket.starthandshake ();
Socket.close ();
System.out.println ();
System.out.println ("No errors, certificate is already trusted");
} catch (Sslexception e) {
System.out.println ();
E.printstacktrace (System.out);
}

x509certificate[] chain = Tm.chain;
if (chain = = null) {
System.out.println ("Could not obtain server certificate chain");
Return
}

BufferedReader reader = new BufferedReader (New InputStreamReader (
system.in));

System.out.println ();
System.out.println ("Server sent" + Chain.length + "certificate (s):");
System.out.println ();
MessageDigest SHA1 = messagedigest.getinstance ("SHA1");
MessageDigest MD5 = messagedigest.getinstance ("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = Chain[i];
System.out.println ("" + (i + 1) + "Subject"
+ CERT.GETSUBJECTDN ());
System.out.println ("Issuer" + Cert.getissuerdn ());
Sha1.update (cert.getencoded ());
System.out.println ("SHA1" + tohexstring (Sha1.digest ()));
Md5.update (cert.getencoded ());
SYSTEM.OUT.PRINTLN ("MD5" + tohexstring (Md5.digest ()));
System.out.println ();
}

System.out
. println ("Enter certificate to add to trusted KeyStore or ' Q ' to quit: [1]");
String line = Reader.readline (). Trim ();
int k;
try {
K = (line.length () = = 0)? 0:integer.parseint (line)-1;
} catch (NumberFormatException e) {
System.out.println ("KeyStore not Changed");
Return
}

X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
Ks.setcertificateentry (alias, cert);

OutputStream out = new FileOutputStream ("Jssecacerts");
Ks.store (out, passphrase);
Out.close ();

System.out.println ();
SYSTEM.OUT.PRINTLN (CERT);
System.out.println ();
System.out
. println ("Added certificate to KeyStore ' Jssecacerts ' using alias '"
+ alias + "'");
}

private static final char[] Hexdigits = "0123456789abcdef". ToCharArray ();

private static String tohexstring (byte[] bytes) {
StringBuilder sb = new StringBuilder (Bytes.length * 3);
for (int b:bytes) {
b &= 0xFF;
Sb.append (Hexdigits[b >> 4]);
Sb.append (Hexdigits[b & 15]);
Sb.append (");
}
return sb.tostring ();
}

private static class Savingtrustmanager implements X509trustmanager {

Private Final X509trustmanager TM;
Private x509certificate[] chain;

Savingtrustmanager (X509trustmanager tm) {
This.tm = TM;
}

Public x509certificate[] Getacceptedissuers () {
throw new Unsupportedoperationexception ();
}

public void checkclienttrusted (x509certificate[] chain, String authtype)
Throws Certificateexception {
throw new Unsupportedoperationexception ();
}

public void checkservertrusted (x509certificate[] chain, String authtype)
Throws Certificateexception {
This.chain = chain;
Tm.checkservertrusted (chain, authtype);
}
}

---get jssecacerts down to jdk/jre/lib/security folder


3, get the way to request results (two development conventions can only use HttpGet)

OAuth2 Java Web implementation PKIX error mu edx

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.