List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Generates a {@link java.security.cert.CertPath CertPath} object and initializes it with the * data read from the {@link java.io.InputStream InputStream} inStream. The data is assumed to be * in the specified encoding./*from w w w. j a v a 2 s .co m*/ * * <p> * The returned certificate path object can be typecast to the {@link M2mCertPath} class. * * @param inStream an {@link java.io.InputStream InputStream} containing the data * @param encoding the encoding used for the data * @return a {@link java.security.cert.CertPath CertPath} initialized with the data from the * {@link java.io.InputStream InputStream} * @exception CertificateException if an exception occurs while decoding or the encoding requested * is not supported */ @Override public CertPath engineGenerateCertPath(InputStream inStream, String encoding) throws CertificateException { if (inStream == null) { throw new CertificateException("input stream is null"); } try { ASN1InputStream aIn = new ASN1InputStream(inStream); ASN1Sequence seq = ASN1Sequence.getInstance(aIn.readObject()); aIn.close(); ASN1Encodable[] objs; List<M2mCertificate> certList; InputStream is; M2mCertificate cert; if (encoding.equals(SupportedEncodings.PKIPATH.getId())) { objs = seq.toArray(); certList = new ArrayList<M2mCertificate>(objs.length); // certificates in PKIPATH encoding is from root to signer but M2MCerPath stores // certificates from signer to root so do it in reverse order. for (int i = objs.length - 1; i >= 0; i--) { is = new ByteArrayInputStream(objs[i].toASN1Primitive().getEncoded()); cert = (M2mCertificate) engineGenerateCertificate(is); certList.add(cert); } } else if (encoding.equals(SupportedEncodings.PKCS7.getId())) { ContentInfo ci = ContentInfo.getInstance(seq); SignedData sd = SignedData.getInstance(ci.getContent()); objs = sd.getCertificates().toArray(); certList = new ArrayList<M2mCertificate>(objs.length); // certificates in PKCS7 encoding is from signer to root, the same order as in M2mCertPath for (int i = 0; i < objs.length; i++) { is = new ByteArrayInputStream(objs[i].toASN1Primitive().getEncoded()); cert = (M2mCertificate) engineGenerateCertificate(is); certList.add(cert); } } else { throw new CertificateException("unknown encoding path: " + encoding); } return new M2mCertPath(certList); } catch (IOException e) { throw new CertificateException("IOException parsing PkiPath data: " + e, e); } }
From source file:cc.arduino.plugins.unowifi.certs.WiFi101Certificate.java
License:Open Source License
private static byte[] getSubjectValueHash(X509Certificate x509) throws NoSuchAlgorithmException, IOException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); ASN1InputStream ais = new ASN1InputStream(x509.getSubjectX500Principal().getEncoded()); while (ais.available() > 0) { ASN1Primitive obj = ais.readObject(); sha1.update(extractPrintableString(obj)); }// ww w. j av a2 s . c o m ais.close(); return sha1.digest(); }
From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * makes RSA public key from bin byte array. * * @param b byte array that contains the key * @return//from w w w . ja va2 s . com * @see JCERSAPublicKey */ public static RSAPublicKey extractBinaryRSAKey(final byte[] b) { RSAPublicKey theKey; try { final ASN1InputStream ais = new ASN1InputStream(b); final Object asnObject = ais.readObject(); final ASN1Sequence sequence = (ASN1Sequence) asnObject; final RSAPublicKeyStructure tempKey = new RSAPublicKeyStructure(sequence); theKey = getRSAPublicKey(tempKey.getModulus(), tempKey.getPublicExponent()); ais.close(); } catch (final IOException e) { logger.warn("Caught exception:" + e.getMessage()); theKey = null; } return theKey; }
From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Mozilla Public License
private DERObject createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); DERObject derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128);/*ww w. j av a2s. co m*/ SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.getDERObject(); }
From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Mozilla Public License
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() .getAlgorithmId();/*from w w w .j a v a 2s .c o m*/ IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId()); cipher.init(1, x509certificate); DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:cn.ieclipse.pde.signer.util.BcpSigner.java
License:Apache License
/** Sign data and write the digital signature to 'out'. */ private static void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out)/* w w w .ja v a2 s.com*/ throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(1); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(sBouncyCastleProvider) .build(privateKey); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build()) .setDirectSignature(true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); }
From source file:com.aaasec.sigserv.cscommon.xmldsig.XMLSign.java
License:EUPL
public static EcdsaSigValue ecdsaSignDataWithSha256(byte[] data, PrivateKey privKey) { try {/*from w w w . jav a2 s . c o m*/ Signature ecdsaSigner = Signature.getInstance("SHA256/ECDSA", "BC"); ecdsaSigner.initSign(privKey, new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes())); ecdsaSigner.update(data); byte[] asn1Signature = ecdsaSigner.sign(); ASN1InputStream a1i = new ASN1InputStream(asn1Signature); ASN1Sequence a1s = ASN1Sequence.getInstance(a1i.readObject()); EcdsaSigValue sigVal = new EcdsaSigValue(a1s); return sigVal; } catch (Exception ex) { } return null; }
From source file:com.aaasec.sigserv.csspsupport.pdfbox.PdfBoxSigUtil.java
License:EUPL
/** * A method that updates the PDF PKCS7 object from the model object with a signature, * certificates and SignedAttributes obtains from an external source. The model contains * /* ww w . j a v a 2 s . co m*/ * <p> * The PKCS7 Signed data found in the model can be created using a different * private key and certificate chain. This method effectively replace the signature * value and certificate with the replacement data obtained from the model. * * @param model A model for this signature replacement operation containing * necessary data for the process. * @return The bytes of an updated ODF signature PKCS7. */ public static byte[] updatePdfPKCS7(PdfSignModel model) { //New variables ByteArrayOutputStream bout = new ByteArrayOutputStream(); DEROutputStream dout = new DEROutputStream(bout); ASN1EncodableVector npkcs7 = new ASN1EncodableVector(); ASN1EncodableVector nsd = new ASN1EncodableVector(); ASN1EncodableVector nsi = new ASN1EncodableVector(); try { ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(model.getSignedData().getEncoded())); // // Basic checks to make sure it's a PKCS#7 SignedData Object // ASN1Primitive pkcs7; try { pkcs7 = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException("Illegal PKCS7"); } if (!(pkcs7 instanceof ASN1Sequence)) { throw new IllegalArgumentException("Illegal PKCS7"); } ASN1Sequence signedData = (ASN1Sequence) pkcs7; ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(PdfObjectIds.ID_PKCS7_SIGNED_DATA)) { throw new IllegalArgumentException("No SignedData"); } //Add Signed data content type to new PKCS7 npkcs7.add(objId); /** * SignedData ::= SEQUENCE { version CMSVersion, digestAlgorithms * DigestAlgorithmIdentifiers, encapContentInfo * EncapsulatedContentInfo, certificates [0] IMPLICIT CertificateSet * OPTIONAL, crls [1] IMPLICIT RevocationInfoChoices OPTIONAL, * signerInfos SignerInfos } */ //Get the SignedData sequence ASN1Sequence signedDataSeq = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject(); int sdObjCount = 0; // the version nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the digestAlgorithms nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the possible ecapsulated content info nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the certificates. The certs are taken from the input parameters to the method //ASN1EncodableVector newCerts = new ASN1EncodableVector(); Certificate[] chain = model.getChain(); ASN1Encodable[] newCerts = new ASN1Encodable[chain.length]; //for (Certificate nCert : model.getCertChain()) { for (int i = 0; i < chain.length; i++) { ASN1InputStream cin = new ASN1InputStream(new ByteArrayInputStream(chain[i].getEncoded())); newCerts[i] = cin.readObject(); } nsd.add(new DERTaggedObject(false, 0, new DERSet(newCerts))); //Step counter past tagged objects while (signedDataSeq.getObjectAt(sdObjCount) instanceof ASN1TaggedObject) { ++sdObjCount; } //SignerInfos is the next object in the sequence of Signed Data (first untagged after certs) ASN1Set signerInfos = (ASN1Set) signedDataSeq.getObjectAt(sdObjCount); if (signerInfos.size() != 1) { throw new IllegalArgumentException("Unsupported multiple signer infos"); } ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); int siCounter = 0; // SignerInfo sequence // // 0 - CMSVersion // 1 - SignerIdentifier (CHOICE IssuerAndSerialNumber SEQUENCE) // 2 - DigestAglorithmIdentifier // 3 - [0] IMPLICIT SignedAttributes SET // 3 - Signature AlgorithmIdentifier // 4 - Signature Value OCTET STRING // 5 - [1] IMPLICIT UnsignedAttributes // //version nsi.add(signerInfo.getObjectAt(siCounter++)); // signing certificate issuer and serial number Certificate sigCert = chain[0]; ASN1EncodableVector issuerAndSerial = getIssuerAndSerial(sigCert); nsi.add(new DERSequence(issuerAndSerial)); siCounter++; //Digest AlgorithmIdentifier nsi.add(signerInfo.getObjectAt(siCounter++)); //Add signed attributes from signature service ASN1InputStream sigAttrIs = new ASN1InputStream(model.getCmsSigAttrBytes()); nsi.add(new DERTaggedObject(false, 0, sigAttrIs.readObject())); //Step counter past tagged objects (because signedAttrs i optional in the input data) while (signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) { siCounter++; } //Signature Alg identifier nsi.add(signerInfo.getObjectAt(siCounter++)); //Add new signature value from signing service nsi.add(new DEROctetString(model.getSignatureBytes())); siCounter++; //Add unsigned Attributes if present if (signerInfo.size() > siCounter && signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) { nsi.add(signerInfo.getObjectAt(siCounter)); } /* * Final Assembly */ // Add the SignerInfo sequence to the SignerInfos set and add this to the SignedData sequence nsd.add(new DERSet(new DERSequence(nsi))); // Add the SignedData sequence as a eplicitly tagged object to the pkcs7 object npkcs7.add(new DERTaggedObject(true, 0, new DERSequence(nsd))); dout.writeObject((new DERSequence(npkcs7))); byte[] pkcs7Bytes = bout.toByteArray(); dout.close(); bout.close(); return pkcs7Bytes; } catch (Exception e) { throw new IllegalArgumentException(e.toString()); } }
From source file:com.aaasec.sigserv.csspsupport.pdfbox.PdfBoxSigUtil.java
License:EUPL
/** * Internal helper method that constructs an IssuerAndSerial object for SignerInfo * based on a signer certificate.// w ww .ja v a 2s . c om * @param sigCert * @return An ASN1EncodableVector holding the IssuerAndSerial ASN.1 sequence. * @throws CertificateEncodingException * @throws IOException */ private static ASN1EncodableVector getIssuerAndSerial(Certificate sigCert) throws CertificateEncodingException, IOException { ASN1EncodableVector issuerAndSerial = new ASN1EncodableVector(); ASN1InputStream ain = new ASN1InputStream(sigCert.getEncoded()); ASN1Sequence certSeq = (ASN1Sequence) ain.readObject(); ASN1Sequence tbsSeq = (ASN1Sequence) certSeq.getObjectAt(0); int counter = 0; while (tbsSeq.getObjectAt(counter) instanceof ASN1TaggedObject) { counter++; } //Get serial ASN1Integer serial = (ASN1Integer) tbsSeq.getObjectAt(counter); counter += 2; ASN1Sequence issuerDn = (ASN1Sequence) tbsSeq.getObjectAt(counter); //Return the issuer field issuerAndSerial.add(issuerDn); issuerAndSerial.add(serial); return issuerAndSerial; }
From source file:com.android.builder.signing.SignedJarBuilder.java
License:Apache License
/** Write the certificate file with a digital signature. */ private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey);/*from w w w . ja va 2s .c om*/ JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(mOutputJar); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); }