/** Read a PKCS#8 format private key. */ private static PrivateKey readPrivateKey(InputStream input) throws IOException, GeneralSecurityException { try { byte[] buffer = new byte[4096]; int size = input.read(buffer); byte[] bytes = Arrays.copyOf(buffer, size); /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */ PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); /* * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm * OID and use that to construct a KeyFactory. */ ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded())); PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject()); String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId(); return KeyFactory.getInstance(algOid).generatePrivate(spec); } finally { input.close(); } }
protected static AlgorithmIdentifier getAlgorithmIdentifier( PublicKey key) throws CertPathValidatorException { try { ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); return info.getAlgorithmId(); } catch (Exception e) { throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e); } }
private static byte[] generateSignatureBlock( SignerConfig signerConfig, byte[] signatureFileBytes) throws InvalidKeyException, CertificateEncodingException, SignatureException { JcaCertStore certs = new JcaCertStore(signerConfig.certificates); X509Certificate signerCert = signerConfig.certificates.get(0); String jcaSignatureAlgorithm = getJcaSignatureAlgorithm( signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm); try { ContentSigner signer = new JcaContentSignerBuilder(jcaSignatureAlgorithm) .build(signerConfig.privateKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().build(), SignerInfoSignatureAlgorithmFinder.INSTANCE) .setDirectSignature(true) .build(signer, new JcaX509CertificateHolder(signerCert))); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(signatureFileBytes), false); ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); } return out.toByteArray(); } catch (OperatorCreationException | CMSException | IOException e) { throw new SignatureException("Failed to generate signature", e); } }
private void parseDG1(byte[] DG1) { try { ASN1InputStream bIn = new ASN1InputStream(DG1); org.bouncycastle.asn1.DERApplicationSpecific app = (DERApplicationSpecific) bIn.readObject(); ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); while (secEnum.hasMoreElements()) { ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement(); byte[] data = seqObj.getEncoded(); if (data[0]== 0x41) { Log.d("type approval number", ByteUtils.bytesToHex(data)); this.set5F01(data); } else if (data[0] == 0x42) { byte[] input = Arrays.copyOfRange(data, 3, data.length); parse5F02(input); } else if (data[0] == 0x7F) { parse7F63(data); } } bIn.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void parseDG11(byte[] DG11) { try { ASN1InputStream bIn = new ASN1InputStream(DG11); org.bouncycastle.asn1.DERApplicationSpecific app = (DERApplicationSpecific) bIn.readObject(); ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); while (secEnum.hasMoreElements()) { ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement(); byte[] data = seqObj.getEncoded(); if (data[0]== 0x7F) { parseDG11(data); } else if (data[0] == (byte) 0x80) { this.setBSN(Arrays.copyOfRange(data, 2, data.length)); } } bIn.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private byte[] parseNonce(byte[] data) { try (ASN1InputStream bIn = new ASN1InputStream(data)) { DERApplicationSpecific app = (DERApplicationSpecific) bIn.readObject(); ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); byte[] tag80 = ((ASN1Primitive) seq.getObjects().nextElement()).getEncoded(); if (tag80[0] == (byte) 0x80) { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] kpi = md.digest(Bytes.concatenate(CAN.getBytes(), Bytes.bytes("00 00 00 03"))); return AESUtils.decryptAESCBC(Bytes.allButFirst(tag80, 2), kpi); } } catch (IOException | NoSuchAlgorithmException e) { Log.e(getClass().getName(), "Failed to parse nonce from response data", e); } return null; }
private PublicKey parseCardMappedPublicKey(byte[] data) { try (ASN1InputStream innerIn = new ASN1InputStream(Bytes.allButFirst(data, 2))) { ASN1Primitive innerObj = innerIn.readObject(); byte[] innerTLV = innerObj.getEncoded(); // tag 82 = Mapping Data if (innerTLV[0] == (byte) 0x82) { // Get the card's Public key return ECCUtils.encodeECCPublicKeyX509(Bytes.allButFirst(innerTLV, 2), curveRef); } } catch (IOException e) { Log.e(getClass().getName(), "Failed to parse card public key", e); } return null; }
private PublicKey parseCardAgreedPublicKey(byte[] data) { try (ASN1InputStream innerIn = new ASN1InputStream(Bytes.allButFirst(data, 2))) { ASN1Primitive innerObj = innerIn.readObject(); byte[] innerTLV = innerObj.getEncoded(); // tag 82 = Mapping Data if (innerTLV[0] == (byte) 0x84) { // Get the card's Public key return ECCUtils.encodeECCPublicKeyX509(Bytes.allButFirst(innerTLV, 2), curveRef); } } catch (IOException e) { Log.e(getClass().getName(), "Failed to parse card public key", e); } return null; }
private byte[] parseAuthCommandResponse(byte[] data) { try (ASN1InputStream innerIn = new ASN1InputStream(Bytes.allButFirst(data, 2))) { ASN1Primitive innerObj = innerIn.readObject(); byte[] innerTLV = innerObj.getEncoded(); // tag 86 = Mapping Data if (innerTLV[0] == (byte) 0x86) { // Get the card's Public key return Bytes.allButFirst(innerTLV, 2); } } catch (IOException e) { Log.e(getClass().getName(), "Failed to parse card token", e); } return null; }
private void parseDG1(byte[] DG1) { try (ASN1InputStream bIn = new ASN1InputStream(DG1)) { org.bouncycastle.asn1.DERApplicationSpecific app = (DERApplicationSpecific) bIn.readObject(); ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); while (secEnum.hasMoreElements()) { ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement(); byte[] data = seqObj.getEncoded(); if (data[0]== 0x41) { Log.d("type approval number", ByteUtils.bytesToHex(data)); this.set5F01(Bytes.allButFirst(data, 1)); } else if (data[0] == 0x42) { byte[] input = Arrays.copyOfRange(data, 3, data.length); parse5F02(input); } else if (data[0] == 0x7F) { parse7F63(data); } } } catch (IOException e) { Log.e(getClass().getName(), e.getMessage(), e); } }
private void parse7F63(byte[] input) { Log.d("input", ByteUtils.bytesToHex(input)); try (ASN1InputStream bIn = new ASN1InputStream(input)) { ASN1Primitive obj = bIn.readObject(); DERApplicationSpecific app = (DERApplicationSpecific) obj; ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); List<byte[]> categories = new ArrayList<>(); while (secEnum.hasMoreElements()) { ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement(); byte[] data = seqObj.getEncoded(); Log.d("5F02data", ByteUtils.bytesToHex(data)); switch (data[0]) { case 0x02: Log.d("#CATEGORY","number of categories:" + data[data.length-1]); break; case (byte) 0x87: categories.add(Arrays.copyOfRange(data, 2, data.length)); break; } } this.set7F63(categories); } catch (IOException e) { Log.e(getClass().getName(), e.getMessage(), e); } }
private void parseDG11(byte[] DG11) { try (ASN1InputStream bIn = new ASN1InputStream(DG11)) { DERApplicationSpecific app = (DERApplicationSpecific) bIn.readObject(); ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); while (secEnum.hasMoreElements()) { ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement(); byte[] data = seqObj.getEncoded(); if (data[0]== 0x7F) { parseDG11(data); } else if (data[0] == (byte) 0x80) { this.setBSN(Arrays.copyOfRange(data, 2, data.length)); } } } catch (IOException e) { Log.e(getClass().getName(), e.getMessage(), e); } }
public void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { Object obj = in.readObject(); if (obj instanceof Hashtable) { this.pkcs12Attributes = (Hashtable)obj; this.pkcs12Ordering = (Vector)in.readObject(); } else { ASN1InputStream aIn = new ASN1InputStream((byte[])obj); DERObjectIdentifier oid; while ((oid = (DERObjectIdentifier)aIn.readObject()) != null) { this.setBagAttribute(oid, aIn.readObject()); } } }
private static ASN1Sequence fromKey( PublicKey pubKey) throws InvalidKeyException { try { SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence)new ASN1InputStream(pubKey.getEncoded()).readObject()); return (ASN1Sequence)new AuthorityKeyIdentifier(info).toASN1Object(); } catch (Exception e) { throw new InvalidKeyException("can't process key: " + e); } }
/** * Add the CRLEntry objects contained in a previous CRL. * * @param other the X509CRL to source the other entries from. */ public void addCRL(X509CRL other) throws CRLException { Set revocations = other.getRevokedCertificates(); if (revocations != null) { Iterator it = revocations.iterator(); while (it.hasNext()) { X509CRLEntry entry = (X509CRLEntry)it.next(); ASN1InputStream aIn = new ASN1InputStream(entry.getEncoded()); try { tbsGen.addCRLEntry(ASN1Sequence.getInstance(aIn.readObject())); } catch (IOException e) { throw new CRLException("exception processing encoding of CRL: " + e.toString()); } } } }
private ASN1Primitive getKeySpec() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1Primitive obj = null; try { baos.write(pubkey.getEncoded()); baos.close(); ASN1InputStream derin = new ASN1InputStream( new ByteArrayInputStream(baos.toByteArray())); obj = derin.readObject(); } catch (IOException ioe) { throw new InvalidKeySpecException(ioe.getMessage()); } return obj; }
private X509AttributeCertificate readDERCertificate( InputStream in) throws IOException { ASN1InputStream dIn = new ASN1InputStream(in); ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = new SignedData(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); return getCertificate(); } } return new X509V2AttributeCertificate(seq.getEncoded()); }
private Certificate readDERCertificate( InputStream in) throws IOException, CertificateParsingException { ASN1InputStream dIn = new ASN1InputStream(in); ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = new SignedData(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); return getCertificate(); } } return new X509CertificateObject( org.bouncycastle.asn1.x509.Certificate.getInstance(seq)); }
private CRL readDERCRL( InputStream in) throws IOException, CRLException { ASN1InputStream dIn = new ASN1InputStream(in); ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = new SignedData(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); return getCRL(); } } return new X509CRLObject(CertificateList.getInstance(seq)); }
private void initFrom(ASN1InputStream aIS) throws IOException { ASN1Primitive obj; while ((obj = aIS.readObject()) != null) { if (obj instanceof DERApplicationSpecific) { setPrivateData((DERApplicationSpecific)obj); } else { throw new IOException("Invalid Input Stream for creating an Iso7816CertificateStructure"); } } }
private void setPrivateData(ASN1InputStream cha) throws IOException { ASN1Primitive obj; obj = cha.readObject(); if (obj instanceof ASN1ObjectIdentifier) { this.oid = (ASN1ObjectIdentifier)obj; } else { throw new IllegalArgumentException("no Oid in CerticateHolderAuthorization"); } obj = cha.readObject(); if (obj instanceof DERApplicationSpecific) { this.accessRights = (DERApplicationSpecific)obj; } else { throw new IllegalArgumentException("No access rights in CerticateHolderAuthorization"); } }
protected void engineInit( byte[] params, String format) throws IOException { if (this.isASN1FormatString(format)) { ASN1InputStream aIn = new ASN1InputStream(params); CAST5CBCParameters p = CAST5CBCParameters.getInstance(aIn.readObject()); keyLength = p.getKeyLength(); iv = p.getIV(); return; } if (format.equals("RAW")) { engineInit(params); return; } throw new IOException("Unknown parameters format in IV parameters object"); }
protected void engineInit( byte[] params, String format) throws IOException { if (format.equals("RAW")) { engineInit(params); return; } if (format.equals("ASN.1")) { ASN1InputStream aIn = new ASN1InputStream(params); IDEACBCPar oct = new IDEACBCPar((ASN1Sequence)aIn.readObject()); engineInit(oct.getIV()); return; } throw new IOException("Unknown parameters format in IV parameters object"); }
private java.security.cert.Certificate readDERCertificate( ASN1InputStream dIn) throws IOException, CertificateParsingException { ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = SignedData.getInstance(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); return getCertificate(); } } return new X509CertificateObject( Certificate.getInstance(seq)); }
private CRL readDERCRL( ASN1InputStream aIn) throws IOException, CRLException { ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sCrlData = SignedData.getInstance(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); return getCRL(); } } return createCRL( CertificateList.getInstance(seq)); }
public void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { Object obj = in.readObject(); if (obj instanceof Hashtable) { this.pkcs12Attributes = (Hashtable)obj; this.pkcs12Ordering = (Vector)in.readObject(); } else { ASN1InputStream aIn = new ASN1InputStream((byte[])obj); ASN1ObjectIdentifier oid; while ((oid = (ASN1ObjectIdentifier)aIn.readObject()) != null) { this.setBagAttribute(oid, aIn.readObject()); } } }
public RespID( PublicKey key) throws OCSPException { try { // TODO Allow specification of a particular provider MessageDigest digest = OCSPUtil.createDigestInstance("SHA1", null); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
/** * Verifies a signature using the sub-filter adbe.x509.rsa_sha1. * @param contentsKey the /Contents key * @param certsKey the /Cert key * @param provider the provider or <code>null</code> for the default provider */ public PdfPKCS7(byte[] contentsKey, byte[] certsKey, String provider) { try { this.provider = provider; X509CertParser cr = new X509CertParser(); cr.engineInit(new ByteArrayInputStream(certsKey)); certs = cr.engineReadAll(); signCerts = certs; signCert = (X509Certificate)certs.iterator().next(); crls = new ArrayList(); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); digest = ((DEROctetString)in.readObject()).getOctets(); if (provider == null) sig = Signature.getInstance("SHA1withRSA"); else sig = Signature.getInstance("SHA1withRSA", provider); sig.initVerify(signCert.getPublicKey()); } catch (Exception e) { throw new ExceptionConverter(e); } }
/** * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007 * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2). * Token is the TSA response without response status, which is usually * handled by the (vendor supplied) TSA request/response interface). * @param timeStampToken byte[] - time stamp token, DER encoded signedData * @return ASN1EncodableVector * @throws IOException */ private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken) throws IOException { if (timeStampToken == null) return null; // @todo: move this together with the rest of the defintions String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken)); ASN1EncodableVector unauthAttributes = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken ASN1Sequence seq = (ASN1Sequence) tempstream.readObject(); v.add(new DERSet(seq)); unauthAttributes.add(new DERSequence(v)); return unauthAttributes; }
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure.getInstance(asn1inputstream.readObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm(); IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber( tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId()); cipher.init(1, x509certificate); DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring); }
/** * return the subject of the given cert as an X509PrincipalObject. */ public static X509Principal getSubjectX509Principal( X509Certificate cert) throws CertificateEncodingException { try { ByteArrayInputStream bIn = new ByteArrayInputStream( cert.getTBSCertificate()); ASN1InputStream aIn = new ASN1InputStream(bIn); TBSCertificateStructure tbsCert = new TBSCertificateStructure( (ASN1Sequence)aIn.readObject()); return new X509Principal(tbsCert.getSubject()); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
/** * return the issuer of the given CRL as an X509PrincipalObject. */ public static X509Principal getIssuerX509Principal( X509CRL crl) throws CRLException { try { ByteArrayInputStream bIn = new ByteArrayInputStream( crl.getTBSCertList()); ASN1InputStream aIn = new ASN1InputStream(bIn); TBSCertList tbsCertList = new TBSCertList( (ASN1Sequence)aIn.readObject()); return new X509Principal(tbsCertList.getIssuer()); } catch (IOException e) { throw new CRLException(e.toString()); } }
private void validOidCheck( String oid) throws IOException { ASN1ObjectIdentifier o = new ASN1ObjectIdentifier(oid); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(o); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); o = (ASN1ObjectIdentifier)aIn.readObject(); if (!o.getId().equals(oid)) { fail("failed oid check for " + oid); } }
private void checkConstruction( NamingAuthority auth, ASN1ObjectIdentifier namingAuthorityID, String namingAuthorityURL, DirectoryString namingAuthorityText) throws IOException { checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText); auth = NamingAuthority.getInstance(auth); checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText); ASN1InputStream aIn = new ASN1InputStream(auth.toASN1Primitive().getEncoded()); ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); auth = NamingAuthority.getInstance(seq); checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText); }
private void checkConstruction( AdmissionSyntax syntax, GeneralName authority, ASN1Sequence admissions) throws IOException { checkValues(syntax, authority, admissions); syntax = AdmissionSyntax.getInstance(syntax); checkValues(syntax, authority, admissions); ASN1InputStream aIn = new ASN1InputStream(syntax.toASN1Primitive().getEncoded()); ASN1Sequence info = (ASN1Sequence)aIn.readObject(); syntax = AdmissionSyntax.getInstance(info); checkValues(syntax, authority, admissions); }