List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream
public ASN1InputStream(byte[] input)
From source file:io.apigee.trireme.crypto.algorithms.DsaKeyPairProvider.java
License:Open Source License
/** * DSA Key Pair format -- the PEM file contains an ASN.1 sequence containing six integers: * p, q, g, y, and x. We construct the appropriate Java data structures after parsing those. *///from w w w . j av a 2s. c om @Override public KeyPair readKeyPair(String algorithm, Reader rdr, char[] passphrase) throws CryptoException, IOException { PemReader reader = new PemReader(rdr); PemObject pemObj = reader.readPemObject(); if (pemObj == null) { throw new CryptoException("Not a valid PEM file"); } if (!DSA_TYPE.equals(pemObj.getType())) { throw new CryptoException("PEM file does not contain a DSA private key"); } ASN1InputStream asnIn = new ASN1InputStream(pemObj.getContent()); ASN1Primitive ao = asnIn.readObject(); if (ao == null) { throw new CryptoException("PEM file does not contain an ASN.1 object"); } if (!(ao instanceof ASN1Sequence)) { throw new CryptoException("PEM file does not contain a sequence"); } ASN1Sequence seq = (ASN1Sequence) ao; if (seq.size() != 6) { throw new CryptoException("ASN.1 sequence is the wrong length for a DSA key"); } DERInteger p = (DERInteger) seq.getObjectAt(1); DERInteger q = (DERInteger) seq.getObjectAt(2); DERInteger g = (DERInteger) seq.getObjectAt(3); DERInteger y = (DERInteger) seq.getObjectAt(4); DERInteger x = (DERInteger) seq.getObjectAt(5); try { KeyFactory factory = KeyFactory.getInstance("DSA"); DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(), g.getValue()); PublicKey pub = factory.generatePublic(pubSpec); DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(), q.getValue(), g.getValue()); PrivateKey key = factory.generatePrivate(keySpec); return new KeyPair(pub, key); } catch (GeneralSecurityException gse) { throw new CryptoException(gse); } }
From source file:it.scoppelletti.spaceship.security.FakeCertificateFactory.java
License:Apache License
@SuppressWarnings({ "deprecation", "TryFinallyCanBeTryWithResources" }) public static X509Certificate create(PublicKey publicKey, FakeKeyPairGeneratorSpec spec) throws IOException, CertificateParsingException { ASN1ObjectIdentifier sigAlgOid;//from www . ja v a2 s . c o m AlgorithmIdentifier sigAlgId; org.bouncycastle.jce.X509Principal subject; ASN1EncodableVector result; Certificate cert; org.bouncycastle.jce.provider.X509CertificateObject x509Cert; TBSCertificate tbsCertificate; ASN1InputStream publicKeyInfoIn = null; V3TBSCertificateGenerator tbsGenerator; byte[] signature; sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption; sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE); signature = new byte[1]; tbsGenerator = new V3TBSCertificateGenerator(); try { publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded()); tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject())); } finally { if (publicKeyInfoIn != null) { publicKeyInfoIn.close(); } } subject = new org.bouncycastle.jce.X509Principal(spec.getSubject().getEncoded()); tbsGenerator.setSerialNumber(new ASN1Integer(spec.getSerialNumber())); tbsGenerator.setSubject(subject); tbsGenerator.setIssuer(subject); tbsGenerator.setStartDate(new Time(spec.getStartDate())); tbsGenerator.setEndDate(new Time(spec.getEndDate())); tbsGenerator.setSignature(sigAlgId); tbsCertificate = tbsGenerator.generateTBSCertificate(); result = new ASN1EncodableVector(); result.add(tbsCertificate); result.add(sigAlgId); result.add(new DERBitString(signature)); cert = Certificate.getInstance(new DERSequence(result)); x509Cert = new org.bouncycastle.jce.provider.X509CertificateObject(cert); return x509Cert; }
From source file:it.trento.comune.j4sign.cms.ExternalSignatureCMSSignedDataGenerator.java
License:Open Source License
/** * Used internally by {@link #makeAlgId(String, byte[])} *//*from www. j a v a 2 s . com*/ private DERObject makeObj(byte[] encoding) throws IOException { if (encoding == null) { return null; } ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); return aIn.readObject(); }
From source file:it.trento.comune.j4sign.cms.ExternalSignatureSignerInfoGenerator.java
License:Open Source License
/** * Generates the SignerInfo CMS structure information for a single signer. * This method has to be called after setting {@link #cert} * {@link #signedBytes}.//from w w w.ja va2 s .c o m * * @return the <code>org.bouncycastle.asn1.cms.SignerInfo</code> object for * a signer. * @throws CertificateEncodingException * @throws IOException */ SignerInfo generate() throws CertificateEncodingException, IOException { AlgorithmIdentifier digAlgId = null; AlgorithmIdentifier encAlgId = null; digAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(this.getDigestAlgOID()), new DERNull()); if (this.getEncryptionAlgOID().equals(CMSSignedDataGenerator.ENCRYPTION_DSA)) { encAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(this.getEncryptionAlgOID())); } else { encAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(this.getEncryptionAlgOID()), new DERNull()); } ASN1OctetString encDigest = new DEROctetString(this.signedBytes); X509Certificate cert = this.getCertificate(); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getTBSCertificate()); ASN1InputStream aIn = new ASN1InputStream(bIn); TBSCertificateStructure tbs = TBSCertificateStructure.getInstance(aIn.readObject()); IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(tbs.getIssuer(), cert.getSerialNumber()); return new SignerInfo(new SignerIdentifier(encSid), digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr); }
From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java
License:Open Source License
private Date parseSigningTime(byte[] bytes, PrintWriter pw) { Date parsedSigningTime = null; try {/* w w w . j a va 2 s . co m*/ ASN1InputStream aIn = new ASN1InputStream(bytes); ASN1Set signedAttributes = (ASN1Set) aIn.readObject(); AttributeTable attr = new AttributeTable(signedAttributes); Iterator iter = attr.toHashtable().values().iterator(); pw.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = (Attribute) iter.next(); pw.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); pw.println("Authenticated time (SERVER local time): " + time.getDate()); parsedSigningTime = time.getDate(); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) pw.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); pw.println("Message Digest (hash of data content): " + formatAsString(md, " ", 16)); } pw.println("\nAttribute dump follows:"); pw.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } } catch (Exception e) { pw.println(e); return null; } pw.flush(); return parsedSigningTime; }
From source file:it.treviso.provincia.freesigner.applet.FreesignerConfFrame.java
License:Open Source License
/** * Returns DERObject extension if the certificate corresponding to given OID<br> * <br>/*from w w w .j a va2 s . com*/ * Restituisce un estensione DERObject dal certificato, corrispoendente * all'OID * * @param cert * certificate * @param oid * String * @throws IOException * @return l'estensione */ private static DERObject getExtensionValue(X509Certificate cert, String oid) throws IOException { byte[] bytes = cert.getExtensionValue(oid); if (bytes == null) { return null; } ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes)); ASN1OctetString otteti = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(otteti.getOctets())); return aIn.readObject(); }
From source file:jcifs.pac.kerberos.KerberosApRequest.java
License:Open Source License
public KerberosApRequest(byte[] token, KerberosKey[] keys) throws PACDecodingException { if (token.length <= 0) throw new PACDecodingException("Empty kerberos ApReq"); DLSequence sequence;// w w w . j ava 2s . c om try { try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) { sequence = ASN1Util.as(DLSequence.class, stream); } } catch (IOException e) { throw new PACDecodingException("Malformed Kerberos Ticket", e); } Enumeration<?> fields = sequence.getObjects(); while (fields.hasMoreElements()) { ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement()); switch (tagged.getTagNo()) { case 0: ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged); if (!pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION))) { throw new PACDecodingException("Invalid kerberos version"); } break; case 1: ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged); if (!msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ))) throw new PACDecodingException("Invalid kerberos request"); break; case 2: DERBitString bitString = ASN1Util.as(DERBitString.class, tagged); this.apOptions = bitString.getBytes()[0]; break; case 3: DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged); if (!derTicket.isConstructed()) throw new PACDecodingException("Malformed Kerberos Ticket"); this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys); break; case 4: // Let's ignore this for now break; default: throw new PACDecodingException("Invalid field in kerberos ticket"); } } }
From source file:jcifs.pac.kerberos.KerberosEncData.java
License:Open Source License
public KerberosEncData(byte[] token, Key key) throws PACDecodingException { ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)); DERApplicationSpecific derToken;/* w ww. jav a 2s. c o m*/ try { derToken = ASN1Util.as(DERApplicationSpecific.class, stream); if (!derToken.isConstructed()) throw new PACDecodingException("Malformed kerberos ticket"); stream.close(); } catch (IOException e) { throw new PACDecodingException("Malformed kerberos ticket", e); } stream = new ASN1InputStream(new ByteArrayInputStream(derToken.getContents())); DLSequence sequence; try { sequence = ASN1Util.as(DLSequence.class, stream); stream.close(); } catch (IOException e) { throw new PACDecodingException("Malformed kerberos ticket", e); } Enumeration<?> fields = sequence.getObjects(); while (fields.hasMoreElements()) { ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields); switch (tagged.getTagNo()) { case 0: // Ticket Flags break; case 1: // Key break; case 2: // Realm DERGeneralString derRealm = ASN1Util.as(DERGeneralString.class, tagged); this.userRealm = derRealm.getString(); break; case 3: // Principal DLSequence principalSequence = ASN1Util.as(DLSequence.class, tagged); DLSequence nameSequence = ASN1Util.as(DLSequence.class, ASN1Util.as(DERTaggedObject.class, principalSequence, 1)); StringBuilder nameBuilder = new StringBuilder(); Enumeration<?> parts = nameSequence.getObjects(); while (parts.hasMoreElements()) { Object part = parts.nextElement(); DERGeneralString stringPart = ASN1Util.as(DERGeneralString.class, part); nameBuilder.append(stringPart.getString()); if (parts.hasMoreElements()) nameBuilder.append('/'); } this.userPrincipalName = nameBuilder.toString(); break; case 4: // Transited Encoding break; case 5: // Kerberos Time // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged, // DERGeneralizedTime.class); break; case 6: // Kerberos Time // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged, // DERGeneralizedTime.class); break; case 7: // Kerberos Time // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged, // DERGeneralizedTime.class); break; case 8: // Kerberos Time // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged, // DERGeneralizedTime.class); break; case 9: // Host Addresses DLSequence adressesSequence = ASN1Util.as(DLSequence.class, tagged); Enumeration<?> adresses = adressesSequence.getObjects(); while (adresses.hasMoreElements()) { DLSequence addressSequence = ASN1Util.as(DLSequence.class, adresses); ASN1Integer addressType = ASN1Util.as(ASN1Integer.class, addressSequence, 0); DEROctetString addressOctets = ASN1Util.as(DEROctetString.class, addressSequence, 1); this.userAddresses = new ArrayList<>(); if (addressType.getValue().intValue() == KerberosConstants.AF_INTERNET) { InetAddress userAddress = null; try { userAddress = InetAddress.getByAddress(addressOctets.getOctets()); } catch (UnknownHostException e) { } this.userAddresses.add(userAddress); } } break; case 10: // Authorization Data DLSequence authSequence = ASN1Util.as(DLSequence.class, tagged); this.userAuthorizations = new ArrayList<>(); Enumeration<?> authElements = authSequence.getObjects(); while (authElements.hasMoreElements()) { DLSequence authElement = ASN1Util.as(DLSequence.class, authElements); ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0)); DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1)); this.userAuthorizations.addAll( KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), key)); } break; default: throw new PACDecodingException("Unknown field " + tagged.getTagNo()); } } }
From source file:jcifs.pac.kerberos.KerberosRelevantAuthData.java
License:Open Source License
public KerberosRelevantAuthData(byte[] token, Key key) throws PACDecodingException { DLSequence authSequence;/* w w w . j a v a2 s .c o m*/ try { try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) { authSequence = ASN1Util.as(DLSequence.class, stream); } } catch (IOException e) { throw new PACDecodingException("Malformed kerberos ticket", e); } this.authorizations = new ArrayList<>(); Enumeration<?> authElements = authSequence.getObjects(); while (authElements.hasMoreElements()) { DLSequence authElement = ASN1Util.as(DLSequence.class, authElements); ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0)); DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1)); this.authorizations .addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), key)); } }
From source file:jcifs.pac.kerberos.KerberosTicket.java
License:Open Source License
public KerberosTicket(byte[] token, byte apOptions, KerberosKey[] keys) throws PACDecodingException { if (token.length <= 0) throw new PACDecodingException("Empty kerberos ticket"); DLSequence sequence;//w ww . j a v a 2 s . c o m try { try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) { sequence = ASN1Util.as(DLSequence.class, stream); } } catch (IOException e) { throw new PACDecodingException("Malformed kerberos ticket", e); } Enumeration<?> fields = sequence.getObjects(); while (fields.hasMoreElements()) { ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields); switch (tagged.getTagNo()) { case 0:// Kerberos version ASN1Integer tktvno = ASN1Util.as(ASN1Integer.class, tagged); if (!tktvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION))) { throw new PACDecodingException("Invalid kerberos version " + tktvno); } break; case 1:// Realm DERGeneralString derRealm = ASN1Util.as(DERGeneralString.class, tagged); this.serverRealm = derRealm.getString(); break; case 2:// Principal DLSequence principalSequence = ASN1Util.as(DLSequence.class, tagged); DLSequence nameSequence = ASN1Util.as(DLSequence.class, ASN1Util.as(DERTaggedObject.class, principalSequence, 1)); StringBuilder nameBuilder = new StringBuilder(); Enumeration<?> parts = nameSequence.getObjects(); while (parts.hasMoreElements()) { Object part = parts.nextElement(); DERGeneralString stringPart = ASN1Util.as(DERGeneralString.class, part); nameBuilder.append(stringPart.getString()); if (parts.hasMoreElements()) nameBuilder.append('/'); } this.serverPrincipalName = nameBuilder.toString(); break; case 3:// Encrypted part DLSequence encSequence = ASN1Util.as(DLSequence.class, tagged); ASN1Integer encType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, encSequence, 0)); DEROctetString encOctets = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, encSequence, 2)); byte[] crypt = encOctets.getOctets(); if (keys == null) { try { keys = new KerberosCredentials().getKeys(); } catch (LoginException e) { throw new PACDecodingException("Login failure", e); } } KerberosKey serverKey = null; for (KerberosKey key : keys) { if (key.getKeyType() == encType.getValue().intValue()) serverKey = key; } if (serverKey == null) { throw new PACDecodingException("Kerberos key not found for eType " + encType.getValue()); } try { byte[] decrypted = KerberosEncData.decrypt(crypt, serverKey, serverKey.getKeyType()); this.encData = new KerberosEncData(decrypted, serverKey); } catch (GeneralSecurityException e) { throw new PACDecodingException("Decryption failed " + serverKey.getKeyType(), e); } break; default: throw new PACDecodingException("Unrecognized field " + tagged.getTagNo()); } } }