Certificate Parser in android

2019-05-21 12:49发布

问题:

I wonder if I am missing some piece of code in this example.I am getting compile-time error on certHeader,certFooter in this class.IF someone can give me a brief idea about it that will be helpful.or IF some one has a better example on certificate parser that will be helpful. I am using this example to parse a certificate.

try 
{ 
    String abc = "-----BEGIN CERTIFICATE-----\n" + "ALneIwerZ5Nu+z1Yjvdco9sOHfkhYW4nL+FIlGDGIS +YsyevB8YN2hBnog7gtQ6PB+sVF6o/1UdU\n" + // lines deleted for brevity "rchFUEChHZ5G7AAk02K7/iyqITc/IPNHHpilTg/NB6QhF9s=\n" + "-----END CERTIFICATE-----";

int headerIndex = abc.indexOf(certHeader); 
    if (headerIndex == -1) 
    {
        throw new CertificateParsingException("cannot find BEGIN CERTIFICATE");
        }
    int startIndex = headerIndex + certHeader.length();

int endIndex = abc.indexOf(certFooter);
if (endIndex == -1) 
{
    throw new CertificateParsingException("cannot find END CERTIFICATE"); }

String cert = abc.substring(startIndex, endIndex);
byte[] certBytes = cert.getBytes();

InputStream in = new Base64InputStream(new ByteArrayInputStream(certBytes));

CertificateFactory certFact = CertificateFactory.getInstance ("X.509");
Certificate certGen = certFact.generateCertificate(in);
X509Certificate x509 = (X509Certificate)
certGen; 
}
catch (Exception e) 
{ 
    Log.e("testapp", "exception: " + e.getMessage());
    } 

回答1:

certHeader and certFooter are supposed to be int variables. From what you've shown us, it doesn't look like you've declared them anywhere.

From the String.indexOf documentation:

Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:

this.charAt(k) == ch