Search in sources :

Example 1 with Any

use of com.google.protobuf2.Any in project geotoolkit by Geomatys.

the class JAXBFeatureTypeReader method getGroupAttributes.

private List<PropertyType> getGroupAttributes(String namespaceURI, Group group, BuildStack stack) throws MismatchedFeatureException {
    if (group == null)
        return Collections.EMPTY_LIST;
    final List<PropertyType> atts = new ArrayList<>();
    final List<Object> particles = group.getParticle();
    for (Object particle : particles) {
        if (particle instanceof JAXBElement) {
            particle = ((JAXBElement) particle).getValue();
        }
        if (particle instanceof Element) {
            final Element ele = (Element) particle;
            final PropertyType att = elementToAttribute(namespaceURI, ele, stack);
            atts.add(att);
        } else if (particle instanceof Any) {
            final Any ele = (Any) particle;
            final SingleAttributeTypeBuilder atb = new SingleAttributeTypeBuilder();
            atb.setName(namespaceURI, Utils.ANY_PROPERTY_NAME);
            atb.setValueClass(Object.class);
            // override properties which are defined
            atb.setMinimumOccurs(ele.getMinOccurs() == null ? 0 : ele.getMinOccurs().intValue());
            final String maxxAtt = ele.getMaxOccurs();
            if ("unbounded".equalsIgnoreCase(maxxAtt)) {
                atb.setMaximumOccurs(Integer.MAX_VALUE);
            } else if (maxxAtt != null) {
                atb.setMaximumOccurs(Integer.parseInt(maxxAtt));
            }
            atts.add(atb.build());
        } else if (particle instanceof GroupRef) {
            final GroupRef ref = (GroupRef) particle;
            final QName groupRef = ref.getRef();
            final NamedGroup ng = xsdContext.findGlobalGroup(groupRef);
            final List<PropertyType> groupAttributes = getGroupAttributes(namespaceURI, ng, stack);
            // change min/max occurences
            int minOcc = ref.getMinOccurs() == null ? 0 : ref.getMinOccurs().intValue();
            int maxOcc = 1;
            String maxxAtt = ref.getMaxOccurs();
            if ("unbounded".equalsIgnoreCase(maxxAtt)) {
                maxOcc = Integer.MAX_VALUE;
            } else if (maxxAtt != null) {
                maxOcc = Integer.parseInt(maxxAtt);
            }
            for (PropertyType pt : groupAttributes) {
                pt = new FeatureTypeBuilder().addProperty(pt).setMinimumOccurs(minOcc).setMaximumOccurs(maxOcc).build();
                atts.add(pt);
            }
        } else if (particle instanceof ExplicitGroup) {
            final ExplicitGroup eg = (ExplicitGroup) particle;
            atts.addAll(getGroupAttributes(namespaceURI, eg, stack));
        } else {
            throw new MismatchedFeatureException("Unexpected TYPE : " + particle);
        }
    }
    return atts;
}
Also used : NamedGroup(org.geotoolkit.xsd.xml.v2001.NamedGroup) FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) QName(javax.xml.namespace.QName) Element(org.geotoolkit.xsd.xml.v2001.Element) JAXBElement(javax.xml.bind.JAXBElement) TopLevelElement(org.geotoolkit.xsd.xml.v2001.TopLevelElement) ArrayList(java.util.ArrayList) PropertyType(org.opengis.feature.PropertyType) JAXBElement(javax.xml.bind.JAXBElement) Any(org.geotoolkit.xsd.xml.v2001.Any) ExplicitGroup(org.geotoolkit.xsd.xml.v2001.ExplicitGroup) SingleAttributeTypeBuilder(org.geotoolkit.feature.SingleAttributeTypeBuilder) MismatchedFeatureException(org.opengis.feature.MismatchedFeatureException) AttributeGroupRef(org.geotoolkit.xsd.xml.v2001.AttributeGroupRef) GroupRef(org.geotoolkit.xsd.xml.v2001.GroupRef)

Example 2 with Any

use of com.google.protobuf2.Any in project jss by dogtagpki.

the class pkcs12 method main.

public static void main(String[] args) {
    try {
        // Read arguments
        if (args.length != 3) {
            System.out.println("Usage: PFX <dbdir> <infile> <outfile>");
            System.exit(-1);
        }
        // open input file for reading
        FileInputStream infile = null;
        try {
            infile = new FileInputStream(args[1]);
        } catch (FileNotFoundException f) {
            System.out.println("Cannot open file " + args[1] + " for reading: " + f.getMessage());
            return;
        }
        int certfile = 0;
        // initialize CryptoManager. This is necessary because there is
        // crypto involved with decoding a PKCS #12 file
        CryptoManager.initialize(args[0]);
        CryptoManager manager = CryptoManager.getInstance();
        // Decode the P12 file
        PFX.Template pfxt = new PFX.Template();
        PFX pfx;
        try (BufferedInputStream is = new BufferedInputStream(infile, 2048)) {
            pfx = (PFX) pfxt.decode(is);
        }
        System.out.println("Decoded PFX");
        // print out information about the top-level PFX structure
        System.out.println("Version: " + pfx.getVersion());
        AuthenticatedSafes authSafes = pfx.getAuthSafes();
        SEQUENCE safeContentsSequence = authSafes.getSequence();
        System.out.println("AuthSafes has " + safeContentsSequence.size() + " SafeContents");
        // Get the password for the old file
        System.out.println("Enter password: ");
        Password pass = Password.readPasswordFromConsole();
        // get new password, which will be used for the new file we create
        // later
        System.out.println("Enter new password:");
        Password newPass = Password.readPasswordFromConsole();
        // Verify the MAC on the PFX.  This is important to be sure
        // it hasn't been tampered with.
        StringBuffer sb = new StringBuffer();
        if (pfx.verifyAuthSafes(pass, sb)) {
            System.out.println("AuthSafes verifies correctly.");
        } else {
            System.out.println("AuthSafes failed to verify because: " + sb);
        }
        // Create a new AuthenticatedSafes. As we read the contents of the
        // old authSafes, we will store them into the new one.  After we have
        // cycled through all the contents, they will all have been copied into
        // the new authSafes.
        AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
        // for(int i=0; i < asSeq.size(); i++) {
        for (int i = 0; i < safeContentsSequence.size(); i++) {
            // The safeContents may or may not be encrypted.  We always send
            // the password in.  It will get used if it is needed.  If the
            // decryption of the safeContents fails for some reason (like
            // a bad password), then this method will throw an exception
            SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);
            System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");
            // Go through all the bags in this SafeContents
            for (int j = 0; j < safeContents.size(); j++) {
                SafeBag safeBag = (SafeBag) safeContents.elementAt(j);
                // The type of the bag is an OID
                System.out.println("\nBag " + j + " has type " + safeBag.getBagType());
                // look for bag attributes
                SET attribs = safeBag.getBagAttributes();
                if (attribs == null) {
                    System.out.println("Bag has no attributes");
                } else {
                    for (int b = 0; b < attribs.size(); b++) {
                        Attribute a = (Attribute) attribs.elementAt(b);
                        if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                            // the friendly name attribute is a nickname
                            BMPString bs = (BMPString) ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                            System.out.println("Friendly Name: " + bs);
                        } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                            // the local key id is used to match a key
                            // to its cert.  The key id is the SHA-1 hash of
                            // the DER-encoded cert.
                            OCTET_STRING os = (OCTET_STRING) ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                            System.out.println("LocalKeyID:");
                        /*
                            AuthenticatedSafes.
                                print_byte_array(os.toByteArray());
							*/
                        } else {
                            System.out.println("Unknown attribute type: " + a.getType().toString());
                        }
                    }
                }
                // now look at the contents of the bag
                ASN1Value val = safeBag.getInterpretedBagContent();
                if (val instanceof PrivateKeyInfo) {
                    // A PrivateKeyInfo contains an unencrypted private key
                    System.out.println("content is PrivateKeyInfo");
                } else if (val instanceof EncryptedPrivateKeyInfo) {
                    // An EncryptedPrivateKeyInfo is, well, an encrypted
                    // PrivateKeyInfo. Usually, strong crypto is used in
                    // an EncryptedPrivateKeyInfo.
                    EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
                    System.out.println("content is EncryptedPrivateKeyInfo, algoid:" + epki.getEncryptionAlgorithm().getOID());
                    // Because we are in a PKCS #12 file, the passwords are
                    // char-to-byte converted in a special way.  We have to
                    // use the special converter class instead of the default.
                    PrivateKeyInfo pki = epki.decrypt(pass, new org.mozilla.jss.pkcs12.PasswordConverter());
                    // import the key into the key3.db
                    CryptoToken tok = manager.getTokenByName("Internal Key Storage Token");
                    CryptoStore store = tok.getCryptoStore();
                    tok.login(new ConsolePasswordCallback());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    pki.encode(baos);
                    store.importPrivateKey(baos.toByteArray(), PrivateKey.RSA);
                    // re-encrypt the PrivateKeyInfo with the new password
                    // and random salt
                    byte[] salt = new byte[PBEAlgorithm.PBE_SHA1_DES3_CBC.getSaltLength()];
                    JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
                    rand.nextBytes(salt);
                    epki = EncryptedPrivateKeyInfo.createPBE(PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);
                    // Overwrite the previous EncryptedPrivateKeyInfo with
                    // this new one we just created using the new password.
                    // This is what will get put in the new PKCS #12 file
                    // we are creating.
                    safeContents.insertElementAt(new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), i);
                    safeContents.removeElementAt(i + 1);
                } else if (val instanceof CertBag) {
                    System.out.println("content is CertBag");
                    CertBag cb = (CertBag) val;
                    if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
                        // this is an X.509 certificate
                        OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
                        Certificate cert = (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
                        cert.getInfo().print(System.out);
                    } else {
                        System.out.println("Unrecognized cert type");
                    }
                } else {
                    System.out.println("content is ANY");
                }
            }
            // Add the new safe contents to the new authsafes
            if (authSafes.safeContentsIsEncrypted(i)) {
                newAuthSafes.addEncryptedSafeContents(AuthenticatedSafes.DEFAULT_KEY_GEN_ALG, newPass, null, AuthenticatedSafes.DEFAULT_ITERATIONS, safeContents);
            } else {
                newAuthSafes.addSafeContents(safeContents);
            }
        }
        // Create new PFX from the new authsafes
        PFX newPfx = new PFX(newAuthSafes);
        // Add a MAC to the new PFX
        newPfx.computeMacData(newPass, null, PFX.DEFAULT_ITERATIONS);
        // write the new PFX out to a file
        FileOutputStream fos = new FileOutputStream(args[2]);
        newPfx.encode(fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) FileNotFoundException(java.io.FileNotFoundException) CryptoManager(org.mozilla.jss.CryptoManager) ANY(org.mozilla.jss.asn1.ANY) ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) BufferedInputStream(java.io.BufferedInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) ConsolePasswordCallback(org.mozilla.jss.util.ConsolePasswordCallback) BMPString(org.mozilla.jss.asn1.BMPString) Password(org.mozilla.jss.util.Password) PFX(org.mozilla.jss.pkcs12.PFX) CryptoToken(org.mozilla.jss.crypto.CryptoToken) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.mozilla.jss.pkcs12.SafeBag) FileInputStream(java.io.FileInputStream) FileNotFoundException(java.io.FileNotFoundException) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes) CryptoStore(org.mozilla.jss.crypto.CryptoStore) CertBag(org.mozilla.jss.pkcs12.CertBag) FileOutputStream(java.io.FileOutputStream) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) PasswordConverter(org.mozilla.jss.pkcs12.PasswordConverter) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.mozilla.jss.pkix.primitive.PrivateKeyInfo) Certificate(org.mozilla.jss.pkix.cert.Certificate)

Example 3 with Any

use of com.google.protobuf2.Any in project jss by dogtagpki.

the class PKCS12Util method create_EPKI_with_PBE_PKCS5_PBES2.

public ASN1Value create_EPKI_with_PBE_PKCS5_PBES2(CryptoToken token, PrivateKey privateKey, Password password) throws Exception {
    CryptoStore store = token.getCryptoStore();
    byte[] bytes = store.getEncryptedPrivateKeyInfo(// password converter
    null, password, // alg.  To avoid mismatch, use AES_256_CBC.
    EncryptionAlgorithm.AES_256_CBC, // iterations (default)
    0, privateKey);
    return new ANY(bytes);
}
Also used : CryptoStore(org.mozilla.jss.crypto.CryptoStore) ANY(org.mozilla.jss.asn1.ANY)

Example 4 with Any

use of com.google.protobuf2.Any in project jss by dogtagpki.

the class PKCS12Util method addKeyBag.

/**
 * Add a private key to the PKCS #12 object.
 *
 * The PKCS12KeyInfo object received comes about in two
 * different scenarios:
 *
 * - The private key could be in encrypted byte[] form (e.g.
 *   when we have merely loaded a PKCS #12 file for inspection
 *   or e.g. to delete a certificate and its associated key).
 *   In this case we simply re-use this encrypted private key
 *   info byte[].
 *
 * - The private key could be a be an NSS PrivateKey handle.  In
 *   this case we must export the PrivateKey from the token to
 *   obtain the EncryptedPrivateKeyInfo.
 *
 * The common final step is to add the encrypted private key
 * data to a "Shrouded Key Bag" to the PKCS #12 object.
 * Unencrypted key material is never seen.
 */
public void addKeyBag(PKCS12KeyInfo keyInfo, Password password, SEQUENCE encSafeContents) throws Exception {
    byte[] keyID = keyInfo.getID();
    logger.debug(" - Key ID: " + Utils.HexEncode(keyID));
    ASN1Value content;
    byte[] epkiBytes = keyInfo.getEncryptedPrivateKeyInfoBytes();
    if (epkiBytes != null) {
        // private key already encrypted
        content = new ANY(epkiBytes);
    } else {
        PrivateKey privateKey = keyInfo.getPrivateKey();
        if (privateKey == null) {
            throw new Exception("Missing private key for " + keyInfo.getFriendlyName());
        }
        CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
        if (keyEncryption == PBEAlgorithm.PBE_SHA1_DES3_CBC) {
            content = create_EPKI_with_PBE_SHA1_DES3_CBC(token, privateKey, password);
        } else if (keyEncryption == PBEAlgorithm.PBE_PKCS5_PBES2) {
            content = create_EPKI_with_PBE_PKCS5_PBES2(token, privateKey, password);
        } else {
            throw new Exception("Unsupported key encryption: " + keyEncryption);
        }
    }
    SET keyAttrs = createKeyBagAttrs(keyInfo);
    SafeBag safeBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG, content, keyAttrs);
    encSafeContents.addElement(safeBag);
}
Also used : ASN1Value(org.mozilla.jss.asn1.ASN1Value) PrivateKey(org.mozilla.jss.crypto.PrivateKey) CryptoToken(org.mozilla.jss.crypto.CryptoToken) SET(org.mozilla.jss.asn1.SET) ANY(org.mozilla.jss.asn1.ANY) SafeBag(org.mozilla.jss.pkcs12.SafeBag) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) CertificateException(java.security.cert.CertificateException) InvalidNameException(javax.naming.InvalidNameException)

Example 5 with Any

use of com.google.protobuf2.Any in project jss by dogtagpki.

the class CRLDistributionPoint method setFullName.

/**
 * Sets the <code>fullName</code> of the <code>DistributionPointName</code>. It may be set to <code>null</code>.
 * If it is set to a non-null value, <code>relativeName</code> will be
 * set to <code>null</code>, because at most one of these two attributes
 * can be specified at a time.
 *
 * @exception GeneralNamesException If an error occurs encoding the
 *                name.
 */
public void setFullName(GeneralNames fullName) throws GeneralNamesException, IOException {
    this.fullName = fullName;
    if (fullName != null) {
        // encode the name to catch any problems with it
        DerOutputStream derOut = new DerOutputStream();
        fullName.encode(derOut);
        try {
            ANY raw = new ANY(derOut.toByteArray());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            raw.encodeWithAlternateTag(Tag.get(0), bos);
            fullNameEncoding = new ANY(bos.toByteArray());
        } catch (InvalidBERException e) {
            // in DerOutputStream
            throw new GeneralNamesException(e.toString());
        }
        this.relativeName = null;
    }
}
Also used : InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) DerOutputStream(org.mozilla.jss.netscape.security.util.DerOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ANY(org.mozilla.jss.asn1.ANY)

Aggregations

Any (com.google.protobuf2.Any)17 ANY (org.mozilla.jss.asn1.ANY)16 ArrayList (java.util.ArrayList)13 Tx (cosmos.gov.v1beta1.Tx)11 SET (org.mozilla.jss.asn1.SET)9 InvalidBERException (org.mozilla.jss.asn1.InvalidBERException)8 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)8 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)7 Attribute (org.mozilla.jss.pkix.primitive.Attribute)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 ASN1Value (org.mozilla.jss.asn1.ASN1Value)6 BMPString (org.mozilla.jss.asn1.BMPString)6 DerOutputStream (org.mozilla.jss.netscape.security.util.DerOutputStream)5 ByteString (com.google.protobuf.ByteString)4 CoinOuterClass (cosmos.base.v1beta1.CoinOuterClass)4 OBJECT_IDENTIFIER (org.mozilla.jss.asn1.OBJECT_IDENTIFIER)4 CryptoToken (org.mozilla.jss.crypto.CryptoToken)4 BufferedInputStream (java.io.BufferedInputStream)3 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3