Is decoding of PKCS8 key from Base64 encoded ASN1 structure fault tolerant?

1.2k views Asked by At

I'm using Spongy Castle library to encode my users private key (PKCS8) into an ASN1 entity and afterwards as Base64 encoded string into a QR code.

One of my colleagues found out that it's possible to change some characters in the Base64 string without damaging the private key. Does the ASN1 format or PKCS8/DER format have some fault tolerance implemented?

//final String encoded = "MIGcAgEBB........lGEOPD2o+H59Qyl"; // original
final String encoded = "MIGcAgEBB........lGEOPD2oXXXXXXX"; // changed!

// decode Base64
final byte[] buffer = Base64.decode(encoded);

// decode ASN1
final ASN1Primitive primitive = ASN1Primitive.fromByteArray(buffer);
final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(primitive);
// read from ASN1
final BigInteger version = ASN1Integer.getInstance(asn1Sequence.getObjectAt(0)).getValue();
final byte[] keyBytes = DEROctetString.getInstance(asn1Sequence.getObjectAt(1)).getOctets();

// get private key from bytes
final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
1

There are 1 answers

0
President James K. Polk On

PKCS#8 is a fairly general container for private keys. Some of the underlying private key structures that it may wrap can contain redundant data. In particular a PKCS#1 RSAPrivateKey has several redundant fields which can be recalculated if necessary. The last 3 fields are completely superfluous. Now, what happens when the consuming software receives a PKCS#8 structure with incorrect or modified data is up to that piece of software.

PKCS#8 does have an encrypted private key info option which can be used to provide anti-tamper cryptography with the correct choice of protection algorithms. If your private key information is ever in an environment where intentional or accidental modification is a legitimate threat then you must take measures to mitigate that threat.