List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:com.android.sdklib.internal.build.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 www. j ava 2s. com 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()); }
From source file:com.android.signapk.SignApk.java
License:Apache License
/** Read a PKCS#8 format private key. */ private static PrivateKey readPrivateKey(File file) throws IOException, GeneralSecurityException { DataInputStream input = new DataInputStream(new FileInputStream(file)); try {/*from w w w. j a v a2 s .c om*/ byte[] bytes = new byte[(int) file.length()]; input.read(bytes); /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */ PKCS8EncodedKeySpec spec = decryptPrivateKey(bytes, file); if (spec == null) { 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(); } }
From source file:com.android.signapk.SignApk.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 . j a v a 2 s . c o m 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 signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey)) .setProvider(sBouncyCastleProvider).build(privateKey); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build()) .setDirectSignature(true).build(signer, 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.awcoleman.BouncyCastleGenericCDRHadoop.StandaloneDecoder.java
License:Apache License
public StandaloneDecoder(String filename) throws IOException { File fileIn = new File(filename); FileInputStream fin = new FileInputStream(fileIn); InputStream is = decompressStream(fin); ASN1InputStream asnin = new ASN1InputStream(is); ASN1Primitive obj = null;//from w w w. j a va 2s. com while ((obj = asnin.readObject()) != null) { CallDetailRecord thisCdr = new CallDetailRecord((ASN1Sequence) obj); System.out.println("CallDetailRecord " + thisCdr.getRecordNumber() + " Calling " + thisCdr.getCallingNumber() + " Called " + thisCdr.getCalledNumber() + " Start Date-Time " + thisCdr.getStartDate() + "-" + thisCdr.getStartTime() + " duration " + thisCdr.getDuration()); } asnin.close(); is.close(); fin.close(); }
From source file:com.bitsofproof.supernode.api.ECKeyPair.java
License:Apache License
public static boolean verify(byte[] hash, byte[] signature, byte[] pub) { ASN1InputStream asn1 = new ASN1InputStream(signature); try {//from w ww . j ava2 s . c o m ECDSASigner signer = new ECDSASigner(); signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(pub), domain)); DLSequence seq = (DLSequence) asn1.readObject(); BigInteger r = ((DERInteger) seq.getObjectAt(0)).getPositiveValue(); BigInteger s = ((DERInteger) seq.getObjectAt(1)).getPositiveValue(); return signer.verifySignature(hash, r, s); } catch (Exception e) { // threat format errors as invalid signatures return false; } finally { try { asn1.close(); } catch (IOException e) { } } }
From source file:com.google.bitcoin.core.ECKey.java
License:Apache License
private static BigInteger extractPrivateKeyFromASN1(byte[] asn1privkey) { // To understand this code, see the definition of the ASN.1 format for EC private keys in the OpenSSL source // code in ec_asn1.c: //// ww w .j a va 2 s . co m // ASN1_SEQUENCE(EC_PRIVATEKEY) = { // ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG), // ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING), // ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0), // ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1) // } ASN1_SEQUENCE_END(EC_PRIVATEKEY) // try { ASN1InputStream decoder = new ASN1InputStream(asn1privkey); DLSequence seq = (DLSequence) decoder.readObject(); checkArgument(seq.size() == 4, "Input does not appear to be an ASN.1 OpenSSL EC private key"); checkArgument(((DERInteger) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE), "Input is of wrong version"); Object obj = seq.getObjectAt(1); byte[] bits = ((ASN1OctetString) obj).getOctets(); decoder.close(); return new BigInteger(1, bits); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen, reading from memory stream. } }
From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java
License:Open Source License
/** * Parses a transport extension from an attestation certificate and returns * a List of HardwareFeatures supported by the security key. The specification of * the HardwareFeatures in the certificate should match their internal definition in * device_auth.proto/*from ww w . j a va 2s .c o m*/ * * <p>The expected transport extension value is a BIT STRING containing the enabled * transports: * * <p>FIDOU2FTransports ::= BIT STRING { * bluetoothRadio(0), -- Bluetooth Classic * bluetoothLowEnergyRadio(1), * uSB(2), * nFC(3) * } * * <p>Note that the BIT STRING must be wrapped in an OCTET STRING. * An extension that encodes BT, BLE, and NFC then looks as follows: * * <p>SEQUENCE (2 elem) * OBJECT IDENTIFIER 1.3.6.1.4.1.45724.2.1.1 * OCTET STRING (1 elem) * BIT STRING (4 bits) 1101 * * @param cert the certificate to parse for extension * @return the supported transports as a List of HardwareFeatures or null if no extension * was found */ public static List<Transports> parseTransportsExtension(X509Certificate cert) throws CertificateParsingException { byte[] extValue = cert.getExtensionValue(TRANSPORT_EXTENSION_OID); LinkedList<Transports> transportsList = new LinkedList<Transports>(); if (extValue == null) { // No transports extension found. return null; } ASN1InputStream ais = new ASN1InputStream(extValue); ASN1Object asn1Object; // Read out the OctetString try { asn1Object = ais.readObject(); ais.close(); } catch (IOException e) { throw new CertificateParsingException("Not able to read object in transports extenion", e); } if (asn1Object == null || !(asn1Object instanceof DEROctetString)) { throw new CertificateParsingException("No Octet String found in transports extension"); } DEROctetString octet = (DEROctetString) asn1Object; // Read out the BitString ais = new ASN1InputStream(octet.getOctets()); try { asn1Object = ais.readObject(); ais.close(); } catch (IOException e) { throw new CertificateParsingException("Not able to read object in transports extension", e); } if (asn1Object == null || !(asn1Object instanceof DERBitString)) { throw new CertificateParsingException("No BitString found in transports extension"); } DERBitString bitString = (DERBitString) asn1Object; byte[] values = bitString.getBytes(); BitSet bitSet = BitSet.valueOf(values); // We might have more defined transports than used by the extension for (int i = 0; i < BITS_IN_A_BYTE; i++) { if (bitSet.get(BITS_IN_A_BYTE - i - 1)) { transportsList.add(Transports.values()[i]); } } return transportsList; }
From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java
License:Open Source License
public static DataMoverSessionID getSessionIDFromCertificate(X509Certificate checkCert) throws IOException { byte[] checkSessionIDBytesEncoded = checkCert .getExtensionValue(X509Extensions.SubjectAlternativeName.toString()); ASN1InputStream decoder = new ASN1InputStream(new ByteArrayInputStream(checkSessionIDBytesEncoded)); DERObject checkObject = decoder.readObject(); DEROctetString checkOctetString = (DEROctetString) checkObject; byte[] checkSessionIDBytes = checkOctetString.getOctets(); DataMoverSessionID checkSessionID = (DataMoverSessionID) ObjectIDFactory .reconstituteFromBytes(checkSessionIDBytes); return checkSessionID; }
From source file:com.infinities.keystone4j.ssl.CRLVerifier.java
License:Apache License
/** * Extracts all CRL distribution point URLs from the * "CRL Distribution Point" extension in a X.509 certificate. If CRL * distribution point extension is unavailable, returns an empty list. *//*from w w w . ja v a 2 s .c o m*/ public static List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateParsingException, IOException { byte[] crldpExt = cert.getExtensionValue(X509Extension.cRLDistributionPoints.getId()); if (crldpExt == null) { return new ArrayList<String>(); } ASN1InputStream oAsnInStream = null; ASN1InputStream oAsnInStream2 = null; try { oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt)); DERObject derObjCrlDP = oAsnInStream.readObject(); DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP; byte[] crldpExtOctets = dosCrlDP.getOctets(); oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets)); DERObject derObj2 = oAsnInStream2.readObject(); CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2); List<String> crlUrls = new ArrayList<String>(); for (DistributionPoint dp : distPoint.getDistributionPoints()) { DistributionPointName dpn = dp.getDistributionPoint(); // Look for URIs in fullName if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for an URI for (int j = 0; j < genNames.length; j++) { if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) { String url = DERIA5String.getInstance(genNames[j].getName()).getString(); crlUrls.add(url); } } } } return crlUrls; } finally { if (oAsnInStream != null) { oAsnInStream.close(); } if (oAsnInStream2 != null) { oAsnInStream2.close(); } } }
From source file:com.infinities.keystone4j.utils.Cms.java
License:Apache License
@SuppressWarnings("rawtypes") public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName) throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException, NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException, CertificateVerificationException { logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName }); Security.addProvider(new BouncyCastleProvider()); X509Certificate signercert = generateCertificate(signingCertFileName); X509Certificate cacert = generateCertificate(caFileName); Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>(); additionalCerts.add(cacert);//w w w . jav a 2s .c om CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert, // certs); if (Base64Verifier.isBase64(sigbytes)) { try { sigbytes = Base64.decode(sigbytes); logger.debug("Signature file is BASE64 encoded"); } catch (Exception ioe) { logger.warn("Problem decoding from b64", ioe); } } // sigbytes = Base64.decode(sigbytes); // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7 // signature --- ASN1InputStream in = null; try { logger.debug("sigbytes size: {}", sigbytes.length); in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject())); Store store = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); int verified = 0; while (it.hasNext()) { X509Certificate cert = null; SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = store.getMatches(signer.getSID()); if (certCollection.isEmpty() && signercert == null) continue; else if (signercert != null) // use a signer cert file for // verification, if it was // provided cert = signercert; else { // use the certificates included in the signature for // verification Iterator certIt = certCollection.iterator(); cert = (X509Certificate) certIt.next(); } // if (signer.verify(new // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) // verified++; } if (verified == 0) { logger.warn(" No signers' signatures could be verified !"); } else if (signercert != null) logger.info("Verified a signature using signer certificate file {}", signingCertFileName); else logger.info("Verified a signature using a certificate in the signature data"); CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent(); byte[] rawcontent = (byte[]) cpb.getContent(); return new String(rawcontent); } catch (Exception ex) { logger.error("Couldn't verify included-content CMS signature", ex); throw new RuntimeException("Couldn't verify included-content CMS signature", ex); } finally { if (in != null) { in.close(); } } }