Example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec.

Prototype

public X509EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new X509EncodedKeySpec with the given encoded key.

Usage

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Check for signature updates./*from  ww w . j  ava 2  s .  com*/
 * 
 * @param context
 *            {@link Context}
 * @param s
 *            signature
 * @param h
 *            hash
 * @return true if ads should be hidden
 */
public static boolean checkSig(final Context context, final String s, final String h) {
    Log.d(TAG, "checkSig(ctx, " + s + ", " + h + ")");
    boolean ret = false;
    try {
        final byte[] publicKey = Base64Coder.decode(KEY);
        final KeyFactory keyFactory = KeyFactory.getInstance(ALGO);
        PublicKey pk = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey));
        Log.d(TAG, "hash: " + h);
        final String cs = s.replaceAll(" |\n|\t", "");
        Log.d(TAG, "read sig: " + cs);
        try {
            byte[] signature = Base64Coder.decode(cs);
            Signature sig = Signature.getInstance(SIGALGO);
            sig.initVerify(pk);
            sig.update(h.getBytes());
            ret = sig.verify(signature);
            Log.d(TAG, "ret: " + ret);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "error reading signature", e);
        }
    } catch (Exception e) {
        Log.e(TAG, "error reading signatures", e);
    }
    if (!ret) {
        Log.i(TAG, "sig: " + s);
    }
    return ret;
}

From source file:com.vmware.demo.SamlService.java

public String validateSAMLResponse(String samlResponse, String samlCert) throws Exception {
    String decodedString = "";
    try {/*from ww w  .j  a  v a2  s  . c  om*/
        decodedString = decodeSAMLResponse(samlResponse);
        InputStream inputStream = new ByteArrayInputStream(decodedString.getBytes("UTF-8"));

        // Parse XML
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        Document document = parserPoolManager.parse(inputStream);
        Element metadataRoot = document.getDocumentElement();

        QName qName = new QName(metadataRoot.getNamespaceURI(), metadataRoot.getLocalName(),
                metadataRoot.getPrefix());

        // Unmarshall document
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(qName);
        Response response = (Response) unmarshaller.unmarshall(metadataRoot);
        Issuer issuer = response.getIssuer();
        logger.info("Parsed response.  Issued:" + response.getIssueInstant().toString() + ", issuer: "
                + issuer.getValue());

        java.security.cert.X509Certificate jX509Cert = SamlUtils.parsePemCertificate(samlCert);
        if (null == jX509Cert) {
            logger.info("Failed to parse cert. " + samlCert);
            return "";
        }

        PublicKey publicCert = jX509Cert.getPublicKey();
        logger.info("Extracted cert.  Cert:" + publicCert);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicCert.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        logger.debug("Key created by provider: " + keyFactory.getProvider().toString());

        // Setup validation
        BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
        Signature signature = response.getSignature();

        // Validate
        try {
            signatureValidator.validate(signature);
            logger.info("Assertion signature validated.");
        } catch (ValidationException e) {
            logger.error("Failed to validate signature of assertion", e);
            throw e;
        }

        // Get decryption key
        RSAPrivateKey privateKey = null;
        BasicX509Credential decryptionCredential = new BasicX509Credential();
        decryptionCredential.setPrivateKey(privateKey);
        StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential);

        // Decrypt assertion
        Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver());
        if (response.getEncryptedAssertions().isEmpty()) {
            logger.info("Nothing to decrypt in assertion.");
        } else {
            Assertion decryptedAssertion;
            try {
                decryptedAssertion = decrypter.decrypt(response.getEncryptedAssertions().get(0));
                logger.info("Assertion decryption succeeded.");
            } catch (DecryptionException e) {
                logger.error("Failed to decrypt assertion", e);
                throw e;
            }

            // Extract attributes, log in output
            List<AttributeStatement> attributeStatements = decryptedAssertion.getAttributeStatements();
            for (int i = 0; i < attributeStatements.size(); i++) {
                List<Attribute> attributes = attributeStatements.get(i).getAttributes();
                for (int x = 0; x < attributes.size(); x++) {
                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                    List<XMLObject> attributeValues = attributes.get(x).getAttributeValues();
                    for (int y = 0; y < attributeValues.size(); y++) {
                        String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
                        logger.info(strAttributeName + " = " + strAttributeValue);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Failed to validate assertion", ex);
        throw ex;
    }
    return decodedString;
}

From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OuyaController.init(this);

    // Initialize ouyaFacade
    ouyaFacade = OuyaFacade.getInstance();
    ouyaFacade.init(this, DEVELOPER_ID);
    userManager = UserManager.getInstance(this);
    playerStates = new ControllerState[OuyaController.MAX_CONTROLLERS];
    for (int i = 0; i < OuyaController.MAX_CONTROLLERS; i++) {
        playerStates[i] = new ControllerState();
    }/*from w w w  .j  a  v  a2 s .c om*/

    // Create the UnityPlayer
    mUnityPlayer = new UnityPlayer(this);
    int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
    boolean trueColor8888 = false;
    mUnityPlayer.init(glesMode, trueColor8888);
    setContentView(R.layout.main);

    // Add the Unity view
    FrameLayout layout = (FrameLayout) findViewById(R.id.unityLayout);
    LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.addView(mUnityPlayer.getView(), 0, lp);

    // Set the focus
    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
    mainLayout.setFocusableInTouchMode(true);

    // Attempt to restore the product and receipt list from the savedInstanceState Bundle
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(PRODUCTS_INSTANCE_STATE_KEY)) {
            Parcelable[] products = savedInstanceState.getParcelableArray(PRODUCTS_INSTANCE_STATE_KEY);
            mProductList = new ArrayList<Product>(products.length);
            for (Parcelable product : products) {
                mProductList.add((Product) product);
            }
            addProducts();
        }
        if (savedInstanceState.containsKey(RECEIPTS_INSTANCE_STATE_KEY)) {
            Parcelable[] receipts = savedInstanceState.getParcelableArray(RECEIPTS_INSTANCE_STATE_KEY);
            mReceiptList = new ArrayList<Receipt>(receipts.length);
            for (Parcelable receipt : receipts) {
                mReceiptList.add((Receipt) receipt);
            }
            addReceipts();
        }
    }

    // Request the product list if it could not be restored from the savedInstanceState Bundle
    if (mProductList == null) {
        requestProducts();
    }

    // Create a PublicKey object from the key data downloaded from the developer portal.
    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(APPLICATION_KEY);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        mPublicKey = keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to create encryption key", e);
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskXMsgRqstHandler.CFAsteriskXMsgRqstLogInHandler.java

public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    final String S_ProcName = "startElement";
    ICFAsteriskSchemaObj schemaObj = null;
    CFAsteriskXMsgSchemaMessageFormatter schemaFormatter = null;
    try {//from ww  w .ja v a 2 s.  c om
        // Common XML Attributes
        String attrId = null;
        // Request Attributes
        String attrLoginId = null;
        String attrDeviceName = null;
        String attrDevEncPWHash = null;
        String attrClusterName = null;
        String attrTenantName = null;
        // Attribute Extraction
        String attrLocalName;
        int numAttrs;
        int idxAttr;
        final String S_LocalName = "LocalName";

        assert qName.equals("RqstLogIn");

        CFAsteriskXMsgRqstHandler xmsgRqstHandler = (CFAsteriskXMsgRqstHandler) getParser();
        if (xmsgRqstHandler == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser()");
        }

        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();

        schemaObj = xmsgRqstHandler.getSchemaObj();
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser().getSchemaObj()");
        }

        schemaObj.connect();

        // Extract Attributes
        numAttrs = attrs.getLength();
        for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) {
            attrLocalName = attrs.getLocalName(idxAttr);
            if (attrLocalName.equals("Id")) {
                if (attrId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("LoginId")) {
                if (attrLoginId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrLoginId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DeviceName")) {
                if (attrDeviceName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDeviceName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DevEncPWHash")) {
                if (attrDevEncPWHash != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDevEncPWHash = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("ClusterName")) {
                if (attrClusterName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrClusterName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("TenantName")) {
                if (attrTenantName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrTenantName = attrs.getValue(idxAttr);
            } else {
                throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(),
                        S_ProcName, getParser().getLocationInfo(), attrLocalName);
            }
        }

        // Ensure that required attributes have values
        if ((attrLoginId == null) || (attrLoginId.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "LoginId");
        }
        if ((attrDeviceName == null) || (attrDeviceName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DeviceName");
        }
        if ((attrDevEncPWHash == null) || (attrDevEncPWHash.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevEncPWHash");
        }
        if ((attrClusterName == null) || (attrClusterName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "ClusterName");
        }
        if ((attrTenantName == null) || (attrTenantName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "TenantName");
        }

        if (schemaObj.getAuthorization() != null) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Back end database schema already authorized against database");
        }

        if (schemaObj.isTransactionOpen()) {
            schemaObj.rollback();
        }

        schemaObj.beginTransaction();

        ICFSecuritySysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }

        ICFSecurityClusterObj resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }

        ICFSecuritySecUserObj authenticatingUser = schemaObj.getSecUserTableObj()
                .readSecUserByULoginIdx(attrLoginId, true);
        if (authenticatingUser == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFSecuritySecDeviceObj device = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(authenticatingUser.getRequiredSecUserId(), attrDeviceName, true);
        if (device == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        String pubKey = device.getOptionalPubKey();
        if ((pubKey == null) || (pubKey.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevicePublicKey");
        }

        byte wrapped[] = Base64.decodeBase64(pubKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DecodedPublicKey");
        }

        byte decodedDevEncPWHash[] = Base64.decodeBase64(attrDevEncPWHash);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        if (cipher == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "cipher");
        }

        cipher.init(Cipher.DECRYPT_MODE, decodedPublicKey);

        byte decryptedPWHash[] = cipher.doFinal(decodedDevEncPWHash);

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(decryptedPWHash);
        byte hash[] = msgDigest.digest();
        byte encodedDoubleHash[] = Base64.encodeBase64(hash);
        String hashedAndEncodedPassword = new String(encodedDoubleHash);

        if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFSecurityClusterObj useCluster = null;
        if (attrClusterName.equals("system")) {
            useCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
            if (useCluster == null) {
                throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                        "ClusterSystem");
            }
            attrTenantName = "system";
        } else {
            useCluster = resolvedCluster;
        }

        ICFSecurityTenantObj useTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(useCluster.getRequiredId(), attrTenantName);
        if (useTenant == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "No such tenant \"" + attrTenantName + "\"");
        }

        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(authenticatingUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFSecurityAuthorization auth = new CFSecurityAuthorization();
        auth.setSecCluster(useCluster);
        auth.setSecTenant(useTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        schemaObj.commit();

        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnLoggedIn("\n\t\t\t",
                        schemaObj.getSecCluster().getRequiredId(),
                        schemaObj.getSecCluster().getRequiredFullDomainName(),
                        schemaObj.getSecTenant().getRequiredId(),
                        schemaObj.getSecTenant().getRequiredTenantName(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredSecUserId(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredLoginId(),
                        schemaObj.getSecSession().getRequiredSecSessionId())
                + "\n" + schemaFormatter.formatRspnXmlPostamble();
        ((CFAsteriskXMsgRqstHandler) getParser()).appendResponse(response);
    } catch (IllegalBlockSizeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (BadPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeyException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchAlgorithmException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeySpecException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (RuntimeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (Error e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFAsteriskXMsgRqstHandler xmsgRqstHandler = ((CFAsteriskXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    }
}

From source file:net.sourceforge.msscodefactory.cffreeswitch.v2_4.CFFreeSwitchXMsgRqstHandler.CFFreeSwitchXMsgRqstLogInHandler.java

public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    final String S_ProcName = "startElement";
    ICFFreeSwitchSchemaObj schemaObj = null;
    CFFreeSwitchXMsgSchemaMessageFormatter schemaFormatter = null;
    try {//w w  w. j  a v  a2  s .c  o m
        // Common XML Attributes
        String attrId = null;
        // Request Attributes
        String attrLoginId = null;
        String attrDeviceName = null;
        String attrDevEncPWHash = null;
        String attrClusterName = null;
        String attrTenantName = null;
        // Attribute Extraction
        String attrLocalName;
        int numAttrs;
        int idxAttr;
        final String S_LocalName = "LocalName";

        assert qName.equals("RqstLogIn");

        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = (CFFreeSwitchXMsgRqstHandler) getParser();
        if (xmsgRqstHandler == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser()");
        }

        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();

        schemaObj = xmsgRqstHandler.getSchemaObj();
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser().getSchemaObj()");
        }

        schemaObj.connect();

        // Extract Attributes
        numAttrs = attrs.getLength();
        for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) {
            attrLocalName = attrs.getLocalName(idxAttr);
            if (attrLocalName.equals("Id")) {
                if (attrId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("LoginId")) {
                if (attrLoginId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrLoginId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DeviceName")) {
                if (attrDeviceName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDeviceName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DevEncPWHash")) {
                if (attrDevEncPWHash != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDevEncPWHash = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("ClusterName")) {
                if (attrClusterName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrClusterName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("TenantName")) {
                if (attrTenantName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrTenantName = attrs.getValue(idxAttr);
            } else {
                throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(),
                        S_ProcName, getParser().getLocationInfo(), attrLocalName);
            }
        }

        // Ensure that required attributes have values
        if ((attrLoginId == null) || (attrLoginId.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "LoginId");
        }
        if ((attrDeviceName == null) || (attrDeviceName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DeviceName");
        }
        if ((attrDevEncPWHash == null) || (attrDevEncPWHash.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevEncPWHash");
        }
        if ((attrClusterName == null) || (attrClusterName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "ClusterName");
        }
        if ((attrTenantName == null) || (attrTenantName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "TenantName");
        }

        if (schemaObj.getAuthorization() != null) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Back end database schema already authorized against database");
        }

        if (schemaObj.isTransactionOpen()) {
            schemaObj.rollback();
        }

        schemaObj.beginTransaction();

        ICFSecuritySysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }

        ICFSecurityClusterObj resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }

        ICFSecuritySecUserObj authenticatingUser = schemaObj.getSecUserTableObj()
                .readSecUserByULoginIdx(attrLoginId, true);
        if (authenticatingUser == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFSecuritySecDeviceObj device = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(authenticatingUser.getRequiredSecUserId(), attrDeviceName, true);
        if (device == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        String pubKey = device.getOptionalPubKey();
        if ((pubKey == null) || (pubKey.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevicePublicKey");
        }

        byte wrapped[] = Base64.decodeBase64(pubKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DecodedPublicKey");
        }

        byte decodedDevEncPWHash[] = Base64.decodeBase64(attrDevEncPWHash);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        if (cipher == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "cipher");
        }

        cipher.init(Cipher.DECRYPT_MODE, decodedPublicKey);

        byte decryptedPWHash[] = cipher.doFinal(decodedDevEncPWHash);

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(decryptedPWHash);
        byte hash[] = msgDigest.digest();
        byte encodedDoubleHash[] = Base64.encodeBase64(hash);
        String hashedAndEncodedPassword = new String(encodedDoubleHash);

        if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFSecurityClusterObj useCluster = null;
        if (attrClusterName.equals("system")) {
            useCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
            if (useCluster == null) {
                throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                        "ClusterSystem");
            }
            attrTenantName = "system";
        } else {
            useCluster = resolvedCluster;
        }

        ICFSecurityTenantObj useTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(useCluster.getRequiredId(), attrTenantName);
        if (useTenant == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "No such tenant \"" + attrTenantName + "\"");
        }

        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(authenticatingUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFSecurityAuthorization auth = new CFSecurityAuthorization();
        auth.setSecCluster(useCluster);
        auth.setSecTenant(useTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        schemaObj.commit();

        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnLoggedIn("\n\t\t\t",
                        schemaObj.getSecCluster().getRequiredId(),
                        schemaObj.getSecCluster().getRequiredFullDomainName(),
                        schemaObj.getSecTenant().getRequiredId(),
                        schemaObj.getSecTenant().getRequiredTenantName(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredSecUserId(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredLoginId(),
                        schemaObj.getSecSession().getRequiredSecSessionId())
                + "\n" + schemaFormatter.formatRspnXmlPostamble();
        ((CFFreeSwitchXMsgRqstHandler) getParser()).appendResponse(response);
    } catch (IllegalBlockSizeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (BadPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeyException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchAlgorithmException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeySpecException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (RuntimeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (Error e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        CFFreeSwitchXMsgRqstHandler xmsgRqstHandler = ((CFFreeSwitchXMsgRqstHandler) getParser());
        schemaFormatter = xmsgRqstHandler.getSchemaMessageFormatter();
        String response = schemaFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFFreeSwitchXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + schemaFormatter.formatRspnXmlPostamble();
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    }
}

From source file:tv.ouya.sample.IapSampleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ouyaFacade = OuyaFacade.getInstance();
    ouyaFacade.init(this, DEVELOPER_ID);

    // Uncomment this line to test against the server using "fake" credits.
    // This will also switch over to a separate "test" purchase history.
    //ouyaFacade.setTestMode();

    setContentView(R.layout.sample_app);

    receiptListView = (ListView) findViewById(R.id.receipts);
    receiptListView.setFocusable(false);

    /*//from w w  w  .  j  a va  2 s . c o m
     * In order to avoid "application not responding" popups, Android demands that long-running operations
     * happen on a background thread. Listener objects provide a way for you to specify what ought to happen
     * at the end of the long-running operation. Examples of this pattern in Android include
     * android.os.AsyncTask.
     */
    findViewById(R.id.gamer_uuid_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fetchGamerUUID();
        }
    });

    // Attempt to restore the product and receipt list from the savedInstanceState Bundle
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(PRODUCTS_INSTANCE_STATE_KEY)) {
            Parcelable[] products = savedInstanceState.getParcelableArray(PRODUCTS_INSTANCE_STATE_KEY);
            mProductList = new ArrayList<Product>(products.length);
            for (Parcelable product : products) {
                mProductList.add((Product) product);
            }
            addProducts();
        }
        if (savedInstanceState.containsKey(RECEIPTS_INSTANCE_STATE_KEY)) {
            Parcelable[] receipts = savedInstanceState.getParcelableArray(RECEIPTS_INSTANCE_STATE_KEY);
            mReceiptList = new ArrayList<Receipt>(receipts.length);
            for (Parcelable receipt : receipts) {
                mReceiptList.add((Receipt) receipt);
            }
            addReceipts();
        }
    }

    // Request the product list if it could not be restored from the savedInstanceState Bundle
    if (mProductList == null) {
        requestProducts();
    }

    // Make sure the receipt ListView starts empty if the receipt list could not be restored
    // from the savedInstanceState Bundle.
    if (mReceiptList == null) {
        receiptListView.setAdapter(new ReceiptAdapter(this, new Receipt[0]));
    }

    // Create a PublicKey object from the key data downloaded from the developer portal.
    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(APPLICATION_KEY);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        mPublicKey = keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to create encryption key", e);
    }
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

public static PublicKey getPublicKeyFromInfo(SubjectPublicKeyInfo o) {
    try {//from w  w  w. j  av a  2 s.  c o  m
        byte[] bytes = o.getEncoded("X509");
        return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(bytes));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Given an X509-formatted encoding of an RSA public key, returns the PublicKey object representing it
 *
 * @param bytes/*from  ww w .ja  va  2s . c o  m*/
 *
 * @return the RSA public key, or null if the RSA algorithm is not available on the system
 */
public static PublicKey getRSAPublicKeyFromEncoded(byte[] bytes) {
    try {
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java

private final PublicKey readPublicKey(String uri) throws LicenseException {
    try {/*w w w  . ja  v  a  2  s . c o m*/

        InputStream inputStream = getClass().getResourceAsStream(uri);
        byte[] bytes = IOUtils.toByteArray(inputStream);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");

        return keyFactory.generatePublic(keySpec);

    } catch (Exception e) {
        throw new LicenseException("Invalid license key! Please contact our support.", e);
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstXMsgRqstHandler.CFAstXMsgRqstLogInHandler.java

public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    final String S_ProcName = "startElement";
    ICFAstSchemaObj schemaObj = null;/*from  w  ww .j a  va2  s.c o m*/
    try {
        // Common XML Attributes
        String attrId = null;
        // Request Attributes
        String attrLoginId = null;
        String attrDeviceName = null;
        String attrDevEncPWHash = null;
        String attrClusterName = null;
        String attrTenantName = null;
        // Attribute Extraction
        String attrLocalName;
        int numAttrs;
        int idxAttr;
        final String S_LocalName = "LocalName";

        assert qName.equals("RqstLogIn");

        CFAstXMsgRqstHandler xmsgRqstHandler = (CFAstXMsgRqstHandler) getParser();
        if (xmsgRqstHandler == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser()");
        }

        schemaObj = xmsgRqstHandler.getSchemaObj();
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "getParser().getSchemaObj()");
        }

        schemaObj.connect();

        // Extract Attributes
        numAttrs = attrs.getLength();
        for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) {
            attrLocalName = attrs.getLocalName(idxAttr);
            if (attrLocalName.equals("Id")) {
                if (attrId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("LoginId")) {
                if (attrLoginId != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrLoginId = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DeviceName")) {
                if (attrDeviceName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDeviceName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("DevEncPWHash")) {
                if (attrDevEncPWHash != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrDevEncPWHash = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("ClusterName")) {
                if (attrClusterName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrClusterName = attrs.getValue(idxAttr);
            } else if (attrLocalName.equals("TenantName")) {
                if (attrTenantName != null) {
                    throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(),
                            S_ProcName, S_LocalName, attrLocalName);
                }
                attrTenantName = attrs.getValue(idxAttr);
            } else {
                throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(),
                        S_ProcName, getParser().getLocationInfo(), attrLocalName);
            }
        }

        // Ensure that required attributes have values
        if ((attrLoginId == null) || (attrLoginId.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "LoginId");
        }
        if ((attrDeviceName == null) || (attrDeviceName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DeviceName");
        }
        if ((attrDevEncPWHash == null) || (attrDevEncPWHash.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevEncPWHash");
        }
        if ((attrClusterName == null) || (attrClusterName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "ClusterName");
        }
        if ((attrTenantName == null) || (attrTenantName.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "TenantName");
        }

        if (schemaObj.getAuthorization() != null) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Back end database schema already authorized against database");
        }

        if (schemaObj.isTransactionOpen()) {
            schemaObj.rollback();
        }

        schemaObj.beginTransaction();

        ICFAstSysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }

        ICFAstClusterObj resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }

        ICFAstSecUserObj authenticatingUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx(attrLoginId,
                true);
        if (authenticatingUser == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFAstSecDeviceObj device = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(authenticatingUser.getRequiredSecUserId(), attrDeviceName, true);
        if (device == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        String pubKey = device.getOptionalPubKey();
        if ((pubKey == null) || (pubKey.length() <= 0)) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DevicePublicKey");
        }

        byte wrapped[] = Base64.decodeBase64(pubKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "DecodedPublicKey");
        }

        byte decodedDevEncPWHash[] = Base64.decodeBase64(attrDevEncPWHash);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        if (cipher == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "cipher");
        }

        cipher.init(Cipher.DECRYPT_MODE, decodedPublicKey);

        byte decryptedPWHash[] = cipher.doFinal(decodedDevEncPWHash);

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(decryptedPWHash);
        byte hash[] = msgDigest.digest();
        byte encodedDoubleHash[] = Base64.encodeBase64(hash);
        String hashedAndEncodedPassword = new String(encodedDoubleHash);

        if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Permission denied");
        }

        ICFAstClusterObj useCluster = null;
        if (attrClusterName.equals("system")) {
            useCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
            if (useCluster == null) {
                throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                        "ClusterSystem");
            }
            attrTenantName = "system";
        } else {
            useCluster = resolvedCluster;
        }

        ICFAstTenantObj useTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(useCluster.getRequiredId(), attrTenantName);
        if (useTenant == null) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "No such tenant \"" + attrTenantName + "\"");
        }

        ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setRequiredContainerSecUser(authenticatingUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFAstAuthorization auth = new CFAstAuthorization();
        auth.setSecCluster(useCluster);
        auth.setSecTenant(useTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        schemaObj.commit();

        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnLoggedIn("\n\t\t\t",
                        schemaObj.getSecCluster().getRequiredId(),
                        schemaObj.getSecCluster().getRequiredFullDomainName(),
                        schemaObj.getSecTenant().getRequiredId(),
                        schemaObj.getSecTenant().getRequiredTenantName(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredSecUserId(),
                        schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredLoginId(),
                        schemaObj.getSecSession().getRequiredSecSessionId())
                + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        ((CFAstXMsgRqstHandler) getParser()).appendResponse(response);
    } catch (IllegalBlockSizeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (BadPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeyException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchAlgorithmException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (NoSuchPaddingException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (InvalidKeySpecException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (RuntimeException e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    } catch (Error e) {
        if (schemaObj != null) {
            schemaObj.rollback();
            schemaObj.setAuthorization(null);
        }
        String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t"
                + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n"
                + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble();
        CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser());
        xmsgRqstHandler.resetResponse();
        xmsgRqstHandler.appendResponse(response);
        xmsgRqstHandler.setCaughtException(true);
    }
}