Hi i am using the following code to parse a certificate details.Everything is fine except a bit problem mentioned below.
package android.net.http;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.security.cert.Certif`enter code here`icate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Base64InputStream;
import android.util.Log;
public class SslCertificate1Activity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
String text = "-----BEGIN CERTIFICATE-----\n"+
"MIIC/TCCAmagAwIBAgIBKjANBgkqhkiG9w0BAQQFADCBqDEiMCAGA1UEAxMZeG1sZ2F0ZXdheS5p\n"+
"dHMudXRleGFzLmVkdTEoMCYGA1UECxMfSW5mb3JtYXRpb24gVGVjaG5vbG9neSBTZXJ2aWNlczEq\n"+
"MCgGA1UEChMhVGhlIFVuaXZlcnNpdHkgb2YgVGV4YXMgYXQgQXVzdGluMQ8wDQYDVQQHEwZBdXN0\n"+
"aW4xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzAeFw0wNDA1MDkwNTMwMTBaFw0wNTA1MDQw\n"+
"NTMwMTBaMIGAMQswCQYDVQQGEwJVUzEOMAwGA1UECBMFVGV4YXMxDzANBgNVBAcTBkF1c3RpbjEq\n"+
"MCgGA1UEChMhVGhlIFVuaXZlcnNpdHkgb2YgVGV4YXMgYXQgQXVzdGluMRMwEQYDVQQLEwpUb29s\n"+
"cyBUZWFtMQ8wDQYDVQQDEwZDbGllbnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJ6PABjb\n"+
"zXUkgo29S4uv1Qz9reo1/tP4pkQTGAldSbtA4hVtA/3sjw2+u3kgxYruAi2cXV2k0RPZhsUZjlDk\n"+
"jMPb/dlY81bD8gqe3lu3ezugJrlArlpfWN6PlufbTjxHSqIA0XD9R5/ZECaUV9dD43K5KdWUCy99\n"+
"YKDiSwVPO9F5AgMBAAGjXTBbMB0GA1UdDgQWBBRkCCpscEXxXu8Ba67p6zdh13ypjzAfBgNVHSME\n"+
"GDAWgBR2RsZH2kSY782kBROo92FAWS6sADAJBgNVHRMEAjAAMA4GA1UdDwQHAwUBEiRIkDANBgkq\n"+
"hkiG9w0BAQQFAAOBgQCtV1NzpdVBs5vyb8yLXNA3hA1LsmE/2QanXG4T3UN93BI4HQzx0idnkN1Y\n"+
"0RAQ1rjGeQ1pk3l2DWsPi9mTkCGmYs/EMLkKOBee9ad3BIG6sKwXgbgLyNLgda+Y1bo+SIomq/a7\n"+
"yP92UHMFEegfS/ssECA+Q3hHuU6in3AqLfWH1w==\n"+
"-----END CERTIFICATE-----";
int startIndex = 0;
String cert = text.substring(startIndex,text.length());
byte[] certBytes = cert.getBytes();
InputStream in = new Base64InputStream(new ByteArrayInputStream(
certBytes), 0);
CertificateFactory certFact = CertificateFactory.getInstance ("X.509");
Certificate certGen = certFact.generateCertificate(in);
X509Certificate x509 = (X509Certificate) certGen;
Log.i("","certificate details:"+x509);
}
catch (Exception e)
{
Log.e("testapp", "exception: " + e.getMessage());
}
}
}
and I am getting android.util.BASE64DataException:bad base-64 at the foloowing line when I launced debugger:-
Certificate certGen = certFact.generateCertificate(in);
Seems like there is something wrong with Base64InputStream.Please help in rectifying the Exception.
Thanks in advance
No, nothing is wrong with Base64InputStream. When in doubt, you should suspect your own code of being incorrect rather than everyone else's.
What's wrong is that you're giving Base64InputStream data that ends with "-----END CERTIFICATE-----" after the padding part.
You should only be passing in the bit between "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----".
It looks like you've started thinking about that already here:
int startIndex = 0;
String cert = text.substring(startIndex,text.length());
... but that code isn't going to do anything - when startIndex is 0, substring is going to return the whole string...
Personally I'd consider doing the Base64 conversion first using the Base64 class to convert the base64 part of the string (you still need to get the substring) to a byte[] and then create a ByteArrayInputStream around that.
Related
I am getting the following error:
scan = new Scanner(new File("file:///android_lib/"+StationNM+".csv"));
I have 아현.csv in the lib folder, but android throws FileNotFoundException.
how can I solve this? adfasdfa
my source is
mport java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Object;
public class model {
public float modelPredict(String StationNM, String UPandDOWN, int day, int hour, int minute)
{
Scanner scan = null;
try {
scan = new Scanner(new File("file:///android_lib/"+StationNM+".csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<String[]> records = new ArrayList<String[]>();
ArrayList<Integer> model_list = new ArrayList<Integer>();
while (scan.hasNext()) {
String[] record;
record = scan.nextLine().split(",");
records.add(record);
}
}
this issue was solved
scan = new Scanner(new File("file:///android_lib/"+StationNM+".csv"));
The File constructor takes filesystem paths. What you are passing:
Is not a filesystem path, as paths do not have schemes like file:// or http:// or content://
Refers to a non-existent directory on the filesystem
I have 아현.csv in the lib folder
Put it in src/main/assets/ of your module. Pass in an AssetManager to your modelPredict() method, and use open() on AssetManager to get an InputStream that you can pass to the Scanner constructor. You get an AssetManager by calling getAssets() on a Context, such as your Activity or Service.
I am trying to use Spongy Castle (v1.47) to create a PKCS10 Certification Request. Spongy Castle behaves exactly the same way as Bouncy Castle, but is more suited to port on Android.
The old (depricated) way as described in Beginning Cryptography with Java by David Hook in chapter 6 works just fine:
package chapter6;
import java.io.OutputStreamWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.util.Vector;
import javax.security.auth.x500.X500Principal;
import org.spongycastle.asn1.DEROctetString;
import org.spongycastle.asn1.DERSet;
import org.spongycastle.asn1.pkcs.Attribute;
import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.spongycastle.asn1.x509.GeneralName;
import org.spongycastle.asn1.x509.GeneralNames;
import org.spongycastle.asn1.x509.X509Extension;
import org.spongycastle.asn1.x509.X509Extensions;
import org.spongycastle.jce.PKCS10CertificationRequest;
import org.spongycastle.openssl.PEMWriter;
import org.spongycastle.jce.provider.BouncyCastleProvider;
/**
* Generation of a basic PKCS #10 request with an extension.
*/
public class PKCS10ExtensionExample {
static {
BouncyCastleProvider prov = new org.spongycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(prov);
}
public static PKCS10CertificationRequest generateRequest( KeyPair pair) throws Exception {
// create a SubjectAlternativeName extension value
GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test#test.test"));
// create the extensions object and add it as an attribute
Vector oids = new Vector();
Vector values = new Vector();
oids.add(X509Extensions.SubjectAlternativeName);
values.add(new X509Extension(false, new DEROctetString(subjectAltName)));
X509Extensions extensions = new X509Extensions(oids, values);
Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions));
return new PKCS10CertificationRequest(
"SHA256withRSA",
new X500Principal("CN=Requested Test Certificate"),
pair.getPublic(),
new DERSet(attribute),
pair.getPrivate());
}
public static void main(String[] args) throws Exception {
// create the keys
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "SC");
kpGen.initialize(1024, Utils.createFixedRandom());
KeyPair pair = kpGen.generateKeyPair();
PKCS10CertificationRequest request = generateRequest(pair);
PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
pemWrt.writeObject(request);
pemWrt.close();
}
}
The small java program prints out the following:
-----BEGIN CERTIFICATE REQUEST-----
MIIBkDCB+gIBADAlMSMwIQYDVQQDExpSZXF1ZXN0ZWQgVGVzdCBDZXJ0aWZpY2F0
ZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAm38mHcNo+YDhe1/XHRa1Cifj
EUwH6SQfqKQcY0sO4gGTVL/U5kBx/y0gIptrnGgUYgfwqptWoKHIqd4PGAuzHfwI
QrTfnYtLnN3dBdnOx/1mZuJ/fCD48H45sTVCcXbypxdwns2PZwgh1rt+jb7TJQii
5TteCLvzzb7FVb/Oc6MCAwEAAaAsMCoGCSqGSIb3DQEJDjEdMBswGQYDVR0RBBIw
EIEOdGVzdEB0ZXN0LnRlc3QwDQYJKoZIhvcNAQELBQADgYEAJexpAYF6RvbYGiNS
kyaF1H8TpDOHaAuIvS4G2Kqw9xXJHYEDiNsQxMc4gWdx6ZNDzc1JYqFBaEV+c/zt
pRPLTRxTi841tLBUAzX7eFQ5EtLwJrKLlHCMXxg3DwcrPjRwidcE87Nl/sOyeT4K
btCXzqpLtklJi/giBl/4L+lQunU=
-----END CERTIFICATE REQUEST-----
The problem is that in the meanwhile (the book is from 2005) most of this Classes are marked as depricated. The new way of creating certificate signing requests is by using Factory Patterns:
package chapter6;
import java.io.OutputStreamWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.util.Vector;
import org.spongycastle.asn1.DERPrintableString;
import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.spongycastle.asn1.x500.X500Name;
import org.spongycastle.asn1.x509.ExtendedKeyUsage;
import org.spongycastle.asn1.x509.KeyPurposeId;
import org.spongycastle.asn1.x509.KeyUsage;
import org.spongycastle.asn1.x509.SubjectPublicKeyInfo;
import org.spongycastle.asn1.x509.X509Extension;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.openssl.PEMWriter;
import org.spongycastle.operator.ContentSigner;
import org.spongycastle.operator.ContentVerifierProvider;
import org.spongycastle.operator.jcajce.JcaContentSignerBuilder;
import org.spongycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
import org.spongycastle.pkcs.PKCS10CertificationRequest;
import org.spongycastle.pkcs.PKCS10CertificationRequestBuilder;
/**
* Generation of a basic PKCS #10 request with an extension.
*/
public class PKCS10ExtensionExampleNew {
static {
BouncyCastleProvider prov = new org.spongycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(prov);
}
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
X500Name subject = new X500Name("CN=Requested Test Certificate");
PKCS10CertificationRequestBuilder certificationRequestBuilder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
certificationRequestBuilder.addAttribute(X509Extension.keyUsage,
new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));
Vector<KeyPurposeId> ekUsages = new Vector<KeyPurposeId>();
ekUsages.add(KeyPurposeId.id_kp_clientAuth);
ekUsages.add(KeyPurposeId.id_kp_serverAuth);
certificationRequestBuilder.addAttribute(X509Extension.extendedKeyUsage, new ExtendedKeyUsage(ekUsages));
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA1WithRSAEncryption");
contentSignerBuilder.setProvider("SC");
ContentSigner contentSigner = contentSignerBuilder.build(pair.getPrivate());
DERPrintableString password = new DERPrintableString("secret123");
certificationRequestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password);
PKCS10CertificationRequest certificationRequest = certificationRequestBuilder.build(contentSigner);
JcaContentVerifierProviderBuilder contentVerifierProviderBuilder = new JcaContentVerifierProviderBuilder();
ContentVerifierProvider contentVerifierProvider = contentVerifierProviderBuilder.build(pair.getPublic());
System.out.println("isSignatureValid? " + certificationRequest.isSignatureValid(contentVerifierProvider));
System.out.println(certificationRequest.getSubject());
return certificationRequest;
}
public static void main(String[] args) throws Exception {
// create the keys
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "SC");
kpGen.initialize(1024, Utils.createFixedRandom());
KeyPair pair = kpGen.generateKeyPair();
PKCS10CertificationRequest request = generateRequest(pair);
PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
pemWrt.writeObject(request);
pemWrt.close();
}
}
The Certificate Request does not get properly build, as it fails on the PEM Generation:
isSignatureValid? true
CN=Requested Test Certificate
Exception in thread "main" org.spongycastle.util.io.pem.PemGenerationException: unknown object passed - can't encode.
at org.spongycastle.openssl.MiscPEMGenerator.createPemObject(MiscPEMGenerator.java:208)
at org.spongycastle.openssl.MiscPEMGenerator.generate(MiscPEMGenerator.java:333)
at org.spongycastle.util.io.pem.PemWriter.writeObject(PemWriter.java:76)
at org.spongycastle.openssl.PEMWriter.writeObject(PEMWriter.java:45)
at be.boeboe.spongycastle.chapter6.PKCS10ExtensionExampleNew.main(PKCS10ExtensionExampleNew.java:71)
Anyone has any idea why the second attempt to create a request failed? I created X509V3Certificate certificates both the old and new way and had no problem there, but putting those differences next to the ones shown here, didn't make me any wiser.
Any help kindly appreciated.
Boeboe
I need help to setup an application in android using eclipse.
I have not used eclipse for JAVA development before so I am a little green as to how this all comes together with android in the mix.
I have a script that I downloaded to test with my web server that has been setup to produce output when accessed (JSON named value pairs at this time).
I am using -
Eclipse IDE for Java Developers
Version: Helios Service Release 2
Build id: 20110218-0911
Android Development Toolkit
Version: 10.0.1.v201103111512-110841
The JAVA code so far -
package new.android.test;
import android.app.Activity;
import android.os.Bundle;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Elemental example for executing a POST request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class search extends Activity {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 80);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/android.php");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
Ok main question is why so many imports?
Also I am getting errors for these imports:
The import org.apache.http.params.SyncBasicHttpParams cannot be resolved
The import org.apache.http.protocol.ImmutableHttpProcessor cannot be resolved
I cannot see these classes in the android.jar.
Is there a more simple example of implementing a transaction against a web server to obtain a namevaluepair (JSON) for using in the android java application?
Those errors are because the classes you are referencing are not a part of the standard Android distribution: see http://developer.android.com/reference/org/apache/http/params/package-summary.html and http://developer.android.com/reference/org/apache/http/protocol/package-summary.html.
Android repackages a specific version of the Apache HTTP library. If you want to use those classes you'll need to include those jars.
I am currently using the following code to encrypt password but it is without using key.
package com.MD5Check;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.os.Bundle;
public class MD5Check extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getSignature();
}
public void getSignature()
{
try {
String s = "aditi9970";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
I would like to hash the password using md5 with key in android.
Can anybody suggest the right way to do this?
MD5 is a hashing algorithm - meaning that the function will only transform data one way (from the original into an md5 hash). I am a little unclear what you mean by 'key' in these circumstances. If you are looking to salt the string before hashing it then you can simply concatenate your original string and your salt.
Alternatively you may wish to look at alternative android encryption techniques. I would start here http://developer.android.com/reference/javax/crypto/package-summary.html
hi i want to display my html image on android emulator, please help
package com.Htmlview;
import ja va.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.webkit.WebView;
public class Htmlview extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
WebView webview = new WebView(this);
setContentView(webview);
try {
String imageString="<html><body>" +
"<h2>Norwegian Mountain Trip</h2>" +
"<img src=\"C:/Users/Public/Pictures/Sample Pictures/pulpit.jpg\" alt=\"Pulpit rock\" width=\"304\" height=\"228\" /></body></html>";
AssetManager mgr = this.getAssets();
InputStream is = mgr.open("index3.html");
BufferedInputStream in = new BufferedInputStream(is); // read the contents of the file
webview.loadData(MessageFormat.format(imageString,arguments),"text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You're never going to be able to access something on your workstation's hard drive from within Android. What you want to do is put the image into the assets folder in your Android app (which will then get bundled into the app) and link to it appropriately with file:///android_assets/. There are other ways of dealing with the issue, but that is the simplest.