I am unable to connect the google storage api through java class. any one provide sample code for this
#SuppressWarnings("serial")
public class GoogleServlet {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private static final String PROJECT_ID = "";
public static String Base64Encoding()
throws java.security.SignatureException, UnsupportedEncodingException {
String access_id = "GOOG37E2YNNQW6FIGGDS ";
String secret_key = URLEncoder.encode("","UTF-8");
String bucket = "";
String version_header = "x-goog-api-version:1";
String project_header = "x-goog-project-id:"+PROJECT_ID;
String canonicalizedResources = "/"+bucket+"/";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 30);
long expiration = calendar.getTimeInMillis();
String stringToSign = URLEncoder.encode("GET\n\n\n"+expiration+"\n"+version_header+"\n"+project_header+"\n"+canonicalizedResources,"UTF-8");
//String stringToSign = URLEncoder.encode("GET\n\n\n"+getdate()+"\n"+version_header+"\n"+project_header+"\n"+canonicalizedResources,"UTF-8");
String authSignature="";
try {
SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(),HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8"));
// base64-encode the hmac
authSignature = new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
authSignature = (access_id +":"+ authSignature);
return authSignature;
}
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();-->ClientConfig cannot be resolved to a type
Client client = Client.create(config);
String authSignature = null;
try {
authSignature = "GOOG1 "+ Base64Encoding();
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
WebResource service = client.resource(getBaseURI());
ClientResponse response = service.accept(MediaType.APPLICATION_XML)-->ClientResponse cannot be resolved to a type
.header("Authorization",authSignature)
.header("Date", getdate())
.header("Content-Length", "0")
.header("x-goog-api-version", "1")
.header("x-goog-project-id", PROJECT_ID)
.get(ClientResponse.class);
System.out.println(response.getClientResponseStatus().getFamily());
System.out.println("response1 :: " + response.getEntity(String.class));
}
private static URI getBaseURI() {
String url = "https://storage.cloud.google.com/mss/";
return UriBuilder.fromUri(url).build();--->The method resource(URI) is undefined for the type Client
}
private static String getdate(){
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z ", new Locale("US"));
Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
format.setCalendar(cal);
return format.format(new Date(0));
}
}
Error:
StringToSign : GET%0A%0A%0A1375378824994%0Ax-goog-api-version%3A1%0Ax-goog-project-id%3A883684764795%0A%2Fmss%2F
Auth Signature : GOOG1 GOOG37E2YNNQW6FIGGDS:3WcA0BQodfq0NrFenFilgJi1tq8=
CLIENT_ERROR
response1 :: <?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>GET
Your secret key is empty:
String secret_key = URLEncoder.encode("","UTF-8");
So signing key is also wrong
SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(),HMAC_SHA1_ALGORITHM);
Related
I am working on an android application for on online taxi service , in which it supports in app calling using sinch SDK. To authorize a client, we need to share our APP_KEY and SECRET_KEY and userId with the sinch server and that's cryptographically signed with the Application Secret.
From their tutorial they have made a class to share these data as base 64 . But once I tried this I got a runtime exception as "bad base-64" like:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tukxi.ride, PID: 17870
java.lang.RuntimeException: bad base-64
at com.general.files.JWT.create(JWT.java:50)
at com.general.files.SinchService$MySinchClientListener.onCredentialsRequired(SinchService.java:252)
at com.sinch.android.rtc.internal.client.DefaultSinchClient$2.onCredentialsRequired(Unknown Source:22)
here is my code :
public static String create(String appKey, String appSecret, String userId) {
JSONObject header = new JSONObject();
JSONObject payload = new JSONObject();
final long issuedAt = System.currentTimeMillis() / 1000;
String kid = "hkdfv1-" + formatDate(issuedAt);
try {
header.put("alg", "HS256");
header.put("typ", "JWT");
header.put("kid", kid);
payload.put("iss","//rtc.sinch.com/applications/" + appKey);
payload.put("sub","//rtc.sinch.com/applications/" + appKey + "/users/" + userId);
payload.put("iat",issuedAt);
payload.put("exp",issuedAt + 600);
payload.put("nonce", UUID.randomUUID());
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
String headerStr = header.toString().trim().replace("\\/","/");
String payloadStr = payload.toString().trim().replace("\\/","/");
String headerBase64 = Base64.encodeToString(headerStr.getBytes(), Base64.NO_PADDING | Base64.NO_WRAP | Base64.DEFAULT);
String payloadBase64 = Base64.encodeToString(payloadStr.getBytes(), Base64.NO_PADDING | Base64.NO_WRAP | Base64.DEFAULT);
String jwtToSign = headerBase64 + "." + payloadBase64;
String jwtSignature;
try {
byte[] origKey = Base64.decode(appSecret, Base64.DEFAULT);
byte[] signingKey = deriveSigningKey(origKey, issuedAt);
final byte[] macData = Hmac.hmacSha256(signingKey, jwtToSign);
String signature = Base64.encodeToString(macData, Base64.NO_PADDING | Base64.NO_WRAP | Base64.DEFAULT);
jwtSignature = jwtToSign + "." + signature;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
return jwtSignature;
}
private static String formatDate(long time) {
String format = "yyyyMMdd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date(time * 1000));
}
private static byte[] deriveSigningKey(byte[] key, long issuedAt) {
return Hmac.hmacSha256(key, formatDate(issuedAt));
}
I have successfully generate pkcs7 signature ECDSAwithSHA256 using C# , but then i failed to verify signature using java
Here is sample class
public class TestVerify {
public static void main(String[] args) {
String Signature = "MIIHFwYJKoZIhvcNAQcCoIIHCDCCBwQCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGgggV3MIIC+TCCAp+gAwIBAgIQDO8RREz6FwFvoLhaHz4ybzAKBggqhkjOPQQDAjB8MQswCQYD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7U2GJqPVrlsD0WGkNfMgBsbkodbeZY4UijGHKeZR+WfyMD+NvtQEmtmyl7odRIeRYYJu6DC0rbaLEfrvEJStHAgh8Sa4TtuF8QkIoxhhWz0E0tmZdtnR79VYzIi8iNrJLokqV2PWmjlIxggJNMIICSQIBATCBhjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBTSEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBAhAEzT+FaK52xhuw/nFgzKdtMA0GCWCGSAFlAwQCAQUAoIGYMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjAxMDI2MTYzNTM0WjArBgsqhkiG9w0BCRACDDEcMBowGDAWBBQDJb1QXtqWMC3CL0+gHkwovig0xTAvBgkqhkiG9w0BCQQxIgQgYN8efCT/4ewuiiMU3leIE9oQPicVR0oD2djP82NuWzswDQYJKoZIhvcNAQEBBQAEggEAsFGcnfha6umvrl+CEkrF10NJYynmAfYWQDnxgt+/B4gJlehJgGvxp3qAMhwCJE2ni4+/kfpRKAPYmxKriUiqDTAZeneV7Mm3gR2msfmSblcmZYHkAcI3S1tTuuWcKulur0boOwzqu6KxISyYtEhpbX9Wg5bdyf4TaLphp+jY4SFBw1EwY4Wdg5dQ6bx2NDauXxyBgOFBxD/5goRpGfM6AvNe9lD416xQty0pvIVjzhRBjkxp4hzSqI7zUA/H/L2nByvthY77MltL3BSqdrEa8/r4CxmMMx0y3Y5kGozbU9ur61QJsxYXmV+NENjhCRo6H6OUhgSHbluTCO1wjvSCZAAAAAA=";
String pdfhash = "faadTnFU4cOBsl+sW98ie7KInSbbw0HDbgFeOcsRCAQ=";
CMSSignedData signedDataTSToken = null;
TimeStampToken tstoken = null;
byte[] sigDataBytes = null;
Date sigDate = null;
CMSSignerHelper cmsHelper = new CMSSignerHelper();
CMSSignedData cmsData;
try {
sigDataBytes = Base64.getDecoder().decode(Signature);
cmsData = new CMSSignedData(sigDataBytes);
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sigDate = formatter.parse(SigDateTime);
byte[] tsTokenDataBytes = Base64.getDecoder().decode(TimestampToken);
signedDataTSToken = new CMSSignedData(tsTokenDataBytes);
tstoken = new TimeStampToken(signedDataTSToken);
verifyCMSSignatureMTID(sigDataBytes, sigDate, TimestampToken, pdfhash);
} catch (Exception e) {
System.out.println("Exception : " + e);
}
}
public static void verifyCMSSignatureMTID(byte[] signature, Date signing_date, String encodedTimestampToken, String PdfHash) throws OperatorCreationException, CMSException, CertificateException, NoSuchAlgorithmException, ParseException, TSPException, IOException, Exception {
String fName="[verifyCMSSignatureMTID] ";
VSInfo vsi=new VSInfo();
String initErr="CMS";
//******************** VERIFY SGNATURE VS SIGNER PUBLICKEY **********************
// Verify signature
byte[] HashByte = Base64.getDecoder().decode(PdfHash);
CMSProcessableByteArray processable = new CMSProcessableByteArray(HashByte);
CMSSignedData cmsData = new CMSSignedData(signature);
X509CertificateHolder certHolder_v=null;
Security.addProvider(new BouncyCastleProvider());
try {
Store store = cmsData.getCertificates();
ByteArrayInputStream stream = new ByteArrayInputStream(signature);
CMSSignedData cms = new CMSSignedData(processable, stream);
SignerInformationStore signers = cms.getSignerInfos();
Collection c_v = signers.getSigners();
Iterator it_v = c_v.iterator();
while (it_v.hasNext()) {
SignerInformation signer_v = (SignerInformation) it_v.next();
Collection certCollection_v = store.getMatches(signer_v.getSID());
Iterator certIt_v = certCollection_v.iterator();
certHolder_v = (X509CertificateHolder) certIt_v.next();
X509Certificate certFromSignedData_v = new JcaX509CertificateConverter().getCertificate(certHolder_v);
if (signer_v.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certFromSignedData_v))) {
System.out.println(fName + "Signature verified");
} else {
System.out.println(fName + "Error CMS200 Signature is invalid");
System.out.println(initErr+"200");
System.out.println("Signature is invalid");
return;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(fName + "Error CMS200 Signature is invalid : " + e);
System.out.println("200");
System.out.println("Signature is invalid");
return;
}
System.out.println("000");
System.out.println("Signature is valid");
return;
}
}
Error
org.bouncycastle.operator.RuntimeOperatorException: exception
obtaining signature: error decoding signature bytes.
However, i have succesfully verify RSAwithSHA256 signature using this method. Can someone help me on this and kindly explain what that error is about. The signature length for those signature is 256byte for RSA and 64byte for ECDSA . is it correct?
The following code uses com.google.code.gson.gson:2.8.5 and org.asynchttpclient.async-http-client:2.5.2 to send JSONs to Azure's Log Analytics. It worked fine until yesterday midnight, but then suddenly started returning HTTP 403 responses. What went wrong?
public class LogAnalyticsSender {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final String HMAC_SHA256_ALG = "HmacSHA256";
static String createAuthorization(String workspaceId, String key, int contentLength, String rfc1123Date) {
try {
// Documentation: https://learn.microsoft.com/en-us/rest/api/loganalytics/create-request
String signature = String.format("POST\n%d\napplication/json\nx-ms-date:%s\n/api/logs", contentLength, rfc1123Date);
Mac mac = Mac.getInstance(HMAC_SHA256_ALG);
mac.init(new SecretKeySpec(DatatypeConverter.parseBase64Binary(key), HMAC_SHA256_ALG));
String hmac = DatatypeConverter.printBase64Binary(mac.doFinal(signature.getBytes(UTF8)));
return String.format("SharedKey %s:%s", workspaceId, hmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
}
final SslEngineFactory defaultSslEngineFactory = (configuration, peerHost, peerPort) -> {
try {
SSLContext sslCtx = SSLContext.getDefault();
SSLEngine sslEngine = sslCtx.createSSLEngine(peerHost, peerPort);
sslEngine.setUseClientMode(true);
return sslEngine;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
};
final String key;
final String workspace;
final Gson gson;
final DefaultAsyncHttpClient httpClient;
public LogAnalyticsSender(String workspaceId, String base64Key, int maxConnections) {
DefaultAsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder().setMaxConnections(maxConnections)
.setThreadPoolName("LogAnalyticsSender").setSslEngineFactory(this.defaultSslEngineFactory).build();
this.key = base64Key;
this.workspace = workspaceId;
this.gson = new GsonBuilder().create();
this.httpClient = new DefaultAsyncHttpClient(config);
}
public CompletableFuture<Response> sendPojo(Object o, String logType) {
String json = this.gson.toJson(o);
return sendRawJson(json, logType);
}
public CompletableFuture<Response> sendPojo(JsonElement element, String logType) {
String json = this.gson.toJson(element);
return sendRawJson(json, logType);
}
public CompletableFuture<Response> sendRawJson(String rawJson, String logType) {
int bodyLength = rawJson.getBytes(UTF8).length;
String nowRfc1123 = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC));
String createAuthorization = createAuthorization(this.workspace, this.key, bodyLength, nowRfc1123);
return this.httpClient.preparePost("https://" + this.workspace + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01").setBody(rawJson)
.addHeader("Authorization", createAuthorization).addHeader("Content-Type", "application/json").addHeader("Log-Type", logType)
.addHeader("x-ms-date", nowRfc1123).execute().toCompletableFuture();
}
public void shutdown() {
this.httpClient.close();
}
}
(answering my own question)
The issue occurred when the date switched from Jul 31 to Aug 1. It turns out that Java's DateTimeFormatter.RFC_1123_DATE_TIME writes the day-of-month as a single digit, and the Log Analytics API doesn't like that.
The solution was to replace the regular RFC 1123 DateTimeFormatter with a pattern that uses two digits:
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss O")
I have a use case to authenticate OAuth1 request which is signed using RSA Private Key and verified at server end with RSA public key.
I found this library from Twitter which helps us authenticate/verify the Oauth signed requests. https://github.com/twitter/joauth
I want to leverage this library for verifying the request from Jersey or Spring MVC action method. The request from client would have been signed using private key. At my end I would use the public key of the client to verify the request. which means RSA-SHA1 algo.
Twitter joauth seem to be useful but I am missing the code that would transform HttpServletRequest to OAuthRequest
The library read-me file suggests this as facility but I could not find a code that does javax.servlet.http.HttpServletRequest --> com.twitter.joauth.OAuthRequest transformation.
The request verification happens in verify method which has following signature.
public VerifierResult verify(UnpackedRequest.OAuth1Request request, String tokenSecret, String consumerSecret);
Secondly I also want to know which is the most appropriate way to use/read RSA public key with twitter joauth when verify method takes String parameter ?
I have never used any library to authenticate users via Twitter. But I have just looked in the UnpackedRequest.OAuth1Request. You can create an instance of this class by filling all parameters. I have written Twitter OAuth Header creator, so you can just use it to fill those parameters or send POST requests directly without a library.
Here all classes what you need:
Signature - to generate an OAuth Signature.
public class Signature {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException
{
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
}
NvpComparator - to sort parameters you need in the header.
public class NvpComparator implements Comparator<NameValuePair> {
#Override
public int compare(NameValuePair arg0, NameValuePair arg1) {
String name0 = arg0.getName();
String name1 = arg1.getName();
return name0.compareTo(name1);
}
}
OAuth - for URL encode.
class OAuth{
...
public static String percentEncode(String s) {
return URLEncoder.encode(s, "UTF-8")
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
}
...
}
HeaderCreator - to create all needed parameters and generate an OAuth header param.
public class HeaderCreator {
private String authorization = "OAuth ";
private String oAuthSignature;
private String oAuthNonce;
private String oAuthTimestamp;
private String oAuthConsumerSecret;
private String oAuthTokenSecret;
public String getAuthorization() {
return authorization;
}
public String getoAuthSignature() {
return oAuthSignature;
}
public String getoAuthNonce() {
return oAuthNonce;
}
public String getoAuthTimestamp() {
return oAuthTimestamp;
}
public HeaderCreator(){}
public HeaderCreator(String oAuthConsumerSecret){
this.oAuthConsumerSecret = oAuthConsumerSecret;
}
public HeaderCreator(String oAuthConsumerSecret, String oAuthTokenSecret){
this(oAuthConsumerSecret);
this.oAuthTokenSecret = oAuthTokenSecret;
}
public String getTwitterServerTime() throws IOException, ParseException {
HttpsURLConnection con = (HttpsURLConnection)
new URL("https://api.twitter.com/oauth/request_token").openConnection();
con.setRequestMethod("HEAD");
con.getResponseCode();
String twitterDate= con.getHeaderField("Date");
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
Date date = formatter.parse(twitterDate);
return String.valueOf(date.getTime() / 1000L);
}
public String generatedSignature(String url, String method, List<NameValuePair> allParams,
boolean withToken) throws SignatureException {
oAuthNonce = String.valueOf(System.currentTimeMillis());
allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
try {
oAuthTimestamp = getTwitterServerTime();
allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
}catch (Exception ex){
//TODO: Log!!
}
Collections.sort(allParams, new NvpComparator());
StringBuffer params = new StringBuffer();
for(int i=0;i<allParams.size();i++)
{
NameValuePair nvp = allParams.get(i);
if (i>0) {
params.append("&");
}
params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
}
String signatureBaseStringTemplate = "%s&%s&%s";
String signatureBaseString = String.format(signatureBaseStringTemplate,
OAuth.percentEncode(method),
OAuth.percentEncode(url),
OAuth.percentEncode(params.toString()));
String compositeKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";
if(withToken) compositeKey+=OAuth.percentEncode(oAuthTokenSecret);
oAuthSignature = Signature.calculateRFC2104HMAC(signatureBaseString, compositeKey);
return oAuthSignature;
}
public String generatedAuthorization(List<NameValuePair> allParams){
authorization = "OAuth ";
Collections.sort(allParams, new NvpComparator());
for(NameValuePair nvm : allParams){
authorization+=nvm.getName()+"="+OAuth.percentEncode(nvm.getValue())+", ";
}
authorization=authorization.substring(0,authorization.length()-2);
return authorization;
}
}
Explain:
1. getTwitterServerTime
In oAuthTimestamp you need not your time of server but the time of a Twitter server. You can optimize it saving this param if you always send requests in the certain Twitter server.
2. HeaderCreator.generatedSignature(...)
url - logically url to twitter API
method - GET or POST. You must use always "POST"
allParams - Parameters which you know to generate signature ("param_name", "param_value");
withToken - if you know oAuthTokenSecret put true. Otherwise false.
3. HeaderCreator.generatedAuthorization(...)
Use this method after generatedSignature(...) to generate an OAuth header string.
allParams - it is parameters which you have used in generatedSignature(...) plus: nonce, signature, timestamp. Always use:
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
Now you can use it to fill UnpackedRequest.OAuth1Request in your library. Also here an example to authenticate user in SpringMVC without the library:
Requests - to send post requests.
public class Requests {
public static String sendPost(String url, String urlParameters, Map<String, String> prop) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
if(prop!=null) {
for (Map.Entry<String, String> entry : prop.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
}
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in;
if(responseCode==200) {
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
}else{
in = new BufferedReader(
new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
twAuth(...) - put it in your controller. Execute it when an user want to authenticate in your site via Twitter.
#RequestMapping(value = "/twauth", method = RequestMethod.GET)
#ResponseBody
public String twAuth(HttpServletResponse response) throws Exception{
try {
String url = "https://api.twitter.com/oauth/request_token";
List<NameValuePair> allParams = new ArrayList<NameValuePair>();
allParams.add(new BasicNameValuePair("oauth_callback", "http://127.0.0.1:8080/twlogin"));
allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
allParams.add(new BasicNameValuePair("oauth_version", "1.0"));
HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
headerCreator.generatedSignature(url,"POST",allParams,false);
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
Map<String, String> props = new HashMap<String, String>();
props.put("Authorization", headerCreator.generatedAuthorization(allParams));
String twitterResponse = Requests.sendPost(url,"",props);
Integer indOAuthToken = twitterResponse.indexOf("oauth_token");
String oAuthToken = twitterResponse.substring(indOAuthToken, twitterResponse.indexOf("&",indOAuthToken));
response.sendRedirect("https://api.twitter.com/oauth/authenticate?" + oAuthToken);
}catch (Exception ex){
//TODO: Log
throw new Exception();
}
return "main";
}
twLogin(...) - put it in your controller. It is callback from Twitter.
#RequestMapping(value = "/twlogin", method = RequestMethod.GET)
public String twLogin(#RequestParam("oauth_token") String oauthToken,
#RequestParam("oauth_verifier") String oauthVerifier,
Model model, HttpServletRequest request){
try {
if(oauthToken==null || oauthToken.equals("") ||
oauthVerifier==null || oauthVerifier.equals(""))
return "main";
String url = "https://api.twitter.com/oauth/access_token";
List<NameValuePair> allParams = new ArrayList<NameValuePair>();
allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
allParams.add(new BasicNameValuePair("oauth_token", oauthToken));
allParams.add(new BasicNameValuePair("oauth_version", "1.0"));
NameValuePair oAuthVerifier = new BasicNameValuePair("oauth_verifier", oauthVerifier);
allParams.add(oAuthVerifier);
HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
headerCreator.generatedSignature(url,"POST",allParams,false);
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
allParams.remove(oAuthVerifier);
Map<String, String> props = new HashMap<String, String>();
props.put("Authorization", headerCreator.generatedAuthorization(allParams));
String twitterResponse = Requests.sendPost(url,"oauth_verifier="+oauthVerifier,props);
//Get user id
Integer startIndexTmp = twitterResponse.indexOf("user_id")+8;
Integer endIndexTmp = twitterResponse.indexOf("&",startIndexTmp);
if(endIndexTmp<=0) endIndexTmp = twitterResponse.length()-1;
Long userId = Long.parseLong(twitterResponse.substring(startIndexTmp, endIndexTmp));
//Do what do you want...
}catch (Exception ex){
//TODO: Log
throw new Exception();
}
}
I have three kinds of files to decode namely .csr and .der and .key files.I am able to decode .der file using the java as below.
public class Base64Decoder {
public static void main(String[] args) throws FileNotFoundException, IOException {
Certificate cert=null;
try{
FileInputStream fis = new FileInputStream("C:/Users/patillat/Downloads/device-ee/csr/00db1234567890A5-ka.der");
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
cert = cf.generateCertificate(bis);
try {
System.out.println("-----BEGIN CERTIFICATE-----");
System.out.println(DatatypeConverter.printBase64Binary(cert.getEncoded()));
System.out.println("-----END CERTIFICATE-----");
//System.out.println("key:"+cert.getPublicKey());
} catch (CertificateEncodingException e) {
e.printStackTrace();
}
System.out.println(cert.toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am able to generate details of .der certificate
In the same way I am not able to decode my .csr file.
Are there any other ways to decode .csr files?
Using BouncyCastle you can easily decode a csr, from binary format.
JcaPKCS10CertificationRequest p10Object = new JcaPKCS10CertificationRequest(byte[] csrBytes);
There are also htlper classes for decoding/decoding to/from PEM format (base64 encoded).
Here's the code that I have used to decode .csr file.
public class CSRInfoDecoder {
private static Logger LOG = Logger.getLogger(CSRInfoDecoder.class.getName());
private static final String COUNTRY = "2.5.4.6";
private static final String STATE = "2.5.4.8";
private static final String LOCALE = "2.5.4.7";
private static final String ORGANIZATION = "2.5.4.10";
private static final String ORGANIZATION_UNIT = "2.5.4.11";
private static final String COMMON_NAME = "2.5.4.3";
private static final String EMAIL = "2.5.4.9";
private static final String csrPEM = "-----BEGIN CERTIFICATE REQUEST-----\n"
+ "MIICxDCCAawCAQAwfzELMAkGA1UEBhMCVVMxETAPBgNVBAgMCElsbGlub2lzMRAw\n"
+ "DgYDVQQHDAdDaGljYWdvMQ4wDAYDVQQKDAVDb2RhbDELMAkGA1UECwwCTkExDjAM\n"
+ "BgNVBAMMBUNvZGFsMR4wHAYJKoZIhvcNAQkBFg9rYmF4aUBjb2RhbC5jb20wggEi\n"
+ "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDSrEF27VvbGi5x7LnPk4hRigAW\n"
+ "1feGeKOmRpHd4j/kUcJZLh59NHJHg5FMF7u9YdZgnMdULawFVezJMLSJYJcCAdRR\n"
+ "hSN+skrQlB6f5wgdkbl6ZfNaMZn5NO1Ve76JppP4gl0rXHs2UkRJeb8lguOpJv9c\n"
+ "tw+Sn6B13j8jF/m/OhIYI8fWhpBYvDXukgADTloCjOIsAvRonkIpWS4d014deKEe\n"
+ "5rhYX67m3H7GtZ/KVtBKhg44ntvuT2fR/wB1FlDws+0gp4edlkDlDml1HXsf4FeC\n"
+ "ogijo6+C9ewC2anpqp9o0CSXM6BT2I0h41PcQPZ4EtAc4ctKSlzTwaH0H9MbAgMB\n"
+ "AAGgADANBgkqhkiG9w0BAQsFAAOCAQEAqfQbrxc6AtjymI3TjN2upSFJS57FqPSe\n"
+ "h1YqvtC8pThm7MeufQmK9Zd+Lk2qnW1RyBxpvWe647bv5HiQaOkGZH+oYNxs1XvM\n"
+ "y5huq+uFPT5StbxsAC9YPtvD28bTH7iXR1b/02AK2rEYT8a9/tCBCcTfaxMh5+fr\n"
+ "maJtj+YPHisjxKW55cqGbotI19cuwRogJBf+ZVE/4hJ5w/xzvfdKjNxTcNr1EyBE\n"
+ "8ueJil2Utd1EnVrWbmHQqnlAznLzC5CKCr1WfmnrDw0GjGg1U6YpjKBTc4MDBQ0T\n"
+ "56ZL2yaton18kgeoWQVgcbK4MXp1kySvdWq0Bc3pmeWSM9lr/ZNwNQ==\n"
+ "-----END CERTIFICATE REQUEST-----\n";
public static void main(String[] args) {
InputStream stream = new ByteArrayInputStream(csrPEM.getBytes(StandardCharsets.UTF_8));
CSRInfoDecoder m = new CSRInfoDecoder();
m.readCertificateSigningRequest(stream);
}
public String readCertificateSigningRequest(InputStream csrStream) {
PKCS10CertificationRequest csr = convertPemToPKCS10CertificationRequest(csrStream);
String compname = null;
if (csr == null) {
LOG.warn("FAIL! conversion of Pem To PKCS10 Certification Request");
} else {
X500Name x500Name = csr.getSubject();
System.out.println("x500Name is: " + x500Name + "\n");
RDN cn = x500Name.getRDNs(BCStyle.EmailAddress)[0];
System.out.println(cn.getFirst().getValue().toString());
System.out.println(x500Name.getRDNs(BCStyle.EmailAddress)[0]);
System.out.println("COUNTRY: " + getX500Field(COUNTRY, x500Name));
System.out.println("STATE: " + getX500Field(STATE, x500Name));
System.out.println("LOCALE: " + getX500Field(LOCALE, x500Name));
System.out.println("ORGANIZATION: " + getX500Field(ORGANIZATION, x500Name));
System.out.println("ORGANIZATION_UNIT: " + getX500Field(ORGANIZATION_UNIT, x500Name));
System.out.println("COMMON_NAME: " + getX500Field(COMMON_NAME, x500Name));
System.out.println("EMAIL: " + getX500Field(EMAIL, x500Name));
}
return compname;
}
private String getX500Field(String asn1ObjectIdentifier, X500Name x500Name) {
RDN[] rdnArray = x500Name.getRDNs(new ASN1ObjectIdentifier(asn1ObjectIdentifier));
String retVal = null;
for (RDN item : rdnArray) {
retVal = item.getFirst().getValue().toString();
}
return retVal;
}
private PKCS10CertificationRequest convertPemToPKCS10CertificationRequest(InputStream pem) {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
PKCS10CertificationRequest csr = null;
ByteArrayInputStream pemStream = null;
pemStream = (ByteArrayInputStream) pem;
Reader pemReader = new BufferedReader(new InputStreamReader(pemStream));
PEMParser pemParser = null;
try {
pemParser = new PEMParser(pemReader);
Object parsedObj = pemParser.readObject();
System.out.println("PemParser returned: " + parsedObj);
if (parsedObj instanceof PKCS10CertificationRequest) {
csr = (PKCS10CertificationRequest) parsedObj;
}
} catch (IOException ex) {
LOG.error("IOException, convertPemToPublicKey", ex);
} finally {
if (pemParser != null) {
IOUtils.closeQuietly(pemParser);
}
}
return csr;
}
}
In the above code, I have converted the csrPem String into a InputStream for my own testing purposes so you can eliminate that step and directly useByteArrayInputStream`.
One can utilize Bouncycastle in order to achieve this. See code snippet below for parsing a String to a PKCS10CertificationRequest. Of course you can replace the ByteArrayInputStream to a arbitrary input stream of your choice.
try (final ByteArrayInputStream bais = new ByteArrayInputStream(csrAsString.getBytes());
final InputStreamReader isr = new InputStreamReader(bais, StandardCharsets.UTF_8);
final PEMParser pem = new PEMParser(isr))
{
PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pem.readObject();
// Do your verification here
}