List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:tv.ouya.sdk.TestOuyaFacade.java
public TestOuyaFacade(Context context, Bundle savedInstanceState, String developerId, byte[] applicationKey) { try {/* ww w .j av a 2 s .co m*/ this.context = context; Log.i("TestOuyaFacade", "TestOuyaFacade.Init(" + developerId + ");"); UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "TestOuyaFacade.Init(" + developerId + ");"); ouyaFacade = OuyaFacade.getInstance(); Init(developerId); // Create a PublicKey object from the key data downloaded from the developer portal. try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); mPublicKey = keyFactory.generatePublic(keySpec); } catch (Exception e) { Log.e(LOG_TAG, "Unable to create encryption key", e); } } catch (Exception ex) { Log.e(LOG_TAG, "TestOuyaFacade constructor exception", ex); } }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarAddDeviceHtml.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//* w ww.jav a 2s. c om*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String S_ProcName = "doPost"; ICFAstSchemaObj schemaObj; HttpSession sess = request.getSession(false); if (sess == null) { sess = request.getSession(true); schemaObj = new CFAstSchemaObj(); sess.setAttribute("SchemaObj", schemaObj); } else { schemaObj = (ICFAstSchemaObj) sess.getAttribute("SchemaObj"); if (schemaObj == null) { response.sendRedirect("CFAstSMWarLoginHtml"); return; } } CFAstAuthorization auth = schemaObj.getAuthorization(); if (auth == null) { response.sendRedirect("CFAstSMWarLoginHtml"); return; } ICFAstSecUserObj secUser = null; ICFAstClusterObj secCluster = null; String clusterDescription = ""; ICFAstSchema dbSchema = null; try { dbSchema = CFAstSchemaPool.getSchemaPool().getInstance(); schemaObj.setBackingStore(dbSchema); schemaObj.beginTransaction(); secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId()); secCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(auth.getSecClusterId()); if (secCluster == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "secCluster"); } clusterDescription = secCluster.getRequiredDescription(); String deviceName = request.getParameter("DeviceName"); if ((deviceName == null) || (deviceName.length() <= 0)) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">"); out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>"); out.println("<H2 style=\"text-align:center\">ERROR</H2>"); out.println("<p style=\"text-align:center\">Device Name must be specified."); out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress() + "</H2>"); out.println("<p>"); out.println("<table style=\"width:90%\">"); out.println( "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>"); out.println("</table>"); out.println( "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button> <button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } ICFAstSecDeviceObj secDev = schemaObj.getSecDeviceTableObj() .readSecDeviceByIdIdx(secUser.getRequiredSecUserId(), deviceName); if (secDev != null) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">"); out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>"); out.println("<H2 style=\"text-align:center\">ERROR</H2>"); out.println("<p style=\"text-align:center\">Device Name \"" + deviceName + "\" already in use."); out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress() + "</H2>"); out.println("<p>"); out.println("<table style=\"width:90%\">"); out.println( "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>"); out.println("</table>"); out.println( "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button> <button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } String publicKey = request.getParameter("PublicKey"); if ((publicKey == null) || (publicKey.length() <= 0)) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">"); out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>"); out.println("<p style=\"text-align:center\">Public Key must be specified."); out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress() + "</H2>"); out.println("<p>"); out.println("<table style=\"width:90%\">"); out.println( "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>"); out.println("</table>"); out.println( "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button> <button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } byte wrapped[] = Base64.decodeBase64(publicKey); 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) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">"); out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>"); out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key."); out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress() + "</H2>"); out.println("<p>"); out.println("<table style=\"width:90%\">"); out.println( "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>"); out.println("</table>"); out.println( "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button> <button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } ICFAstClusterObj systemCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system"); ICFAstTenantObj systemTenant = schemaObj.getTenantTableObj() .readTenantByUNameIdx(systemCluster.getRequiredId(), "system"); ICFAstSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system"); ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance(); ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit(); editSystemSession.setRequiredContainerSecUser(systemUser); editSystemSession.setRequiredStart(Calendar.getInstance()); systemSession = editSystemSession.create(); editSystemSession.endEdit(); CFAstAuthorization secAuth = new CFAstAuthorization(); secAuth.setSecCluster(systemCluster); secAuth.setSecTenant(systemTenant); secAuth.setSecSession(systemSession); schemaObj.setAuthorization(secAuth); secDev = schemaObj.getSecDeviceTableObj().newInstance(); ICFAstSecDeviceEditObj editDev = secDev.beginEdit(); editDev.setRequiredContainerSecUser(secUser); editDev.setRequiredDevName(deviceName); editDev.setOptionalPubKey(publicKey); secDev = editDev.create(); editDev.endEdit(); if (null == secUser.getOptionalLookupDefDev()) { ICFAstSecUserEditObj editSecUser = secUser.beginEdit(); editSecUser.setOptionalLookupDefDev(secDev); editSecUser.update(); editSecUser.endEdit(); } editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit(); editSystemSession.setOptionalFinish(Calendar.getInstance()); editSystemSession.update(); editSystemSession.endEdit(); schemaObj.commit(); schemaObj.setAuthorization(auth); response.sendRedirect("CFAstSMWarSecurityMainHtml"); } catch (InvalidKeySpecException e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">"); out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>"); out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key."); out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress() + "</H2>"); out.println("<p>"); out.println("<table style=\"width:90%\">"); out.println( "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>"); out.println("</table>"); out.println( "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button> <button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); } catch (NoSuchAlgorithmException e) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Caught NoSuchAlgorithmException -- " + e.getMessage(), e); } catch (RuntimeException e) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Caught RuntimeException -- " + e.getMessage(), e); } finally { schemaObj.setAuthorization(auth); if (dbSchema != null) { try { if (schemaObj.isTransactionOpen()) { schemaObj.rollback(); } } catch (RuntimeException e) { } schemaObj.setBackingStore(null); CFAstSchemaPool.getSchemaPool().releaseInstance(dbSchema); } } }
From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java
private Cipher getRsaCipher(String key) { try {// ww w .j a v a 2 s. c o m KeyFactory keyFactory = KeyFactory.getInstance("RSA"); String keyString = key.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", ""); byte[] keyData = Base64.getDecoder().decode(keyString); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData); PublicKey publicKey = keyFactory.generatePublic(keySpec); logger.debug("[{}] Miniserver public key: {}", debugId, publicKey); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.PUBLIC_KEY, publicKey); logger.debug("[{}] Initialized RSA public key cipher", debugId); return cipher; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e) { setError(LxOfflineReason.INTERNAL_ERROR, "Exception enabling RSA cipher: " + e.getMessage()); return null; } }
From source file:in.neoandroid.neoupdate.neoUpdate.java
private boolean checkSignature(String jsonContent, String sign) { Log.d(TAG, "JSON: " + jsonContent); if (sign == null) return false; final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf" + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY" + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ" + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW" + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns" + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB"; try {//from w ww . j a v a 2s.c o m byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP); X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey publicKey = kf.generatePublic(publicSpec); Signature signer = Signature.getInstance("SHA1withRSA"); signer.initVerify(publicKey); signer.update(jsonContent.getBytes(), 0, jsonContent.length()); return signer.verify(Base64.decode(sign, Base64.NO_WRAP)); } catch (Exception e) { } return false; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system, SecurityService securityService) throws GemFireSecurityException, IOException { boolean requireAuthentication = securityService.isClientSecurityRequired(); Properties credentials = null; try {//from w w w . ja v a 2 s. c o m byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { DataSerializer.readProperties(dis); // ignore the credentials } } else if (secureMode == CREDENTIALS_DHENCRYPT) { boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used String skAlgo = DataSerializer.readString(dis); // Get the public key of the other side byte[] keyBytes = DataSerializer.readByteArray(dis); byte[] challenge = null; PublicKey pubKey = null; if (requireAuthentication) { // Generate PublicKey from encoded form X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); pubKey = keyFact.generatePublic(x509KeySpec); // Send the public key to other side keyBytes = dhPublicKey.getEncoded(); challenge = new byte[64]; random.nextBytes(challenge); // If the server has to also authenticate itself then // sign the challenge from client. if (sendAuthentication) { // Get the challenge string from client byte[] clientChallenge = DataSerializer.readByteArray(dis); if (privateKeyEncrypt == null) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE .toLocalizedString()); } // Sign the challenge from client and send it to the client Signature sig = Signature.getInstance(privateKeySignAlgo); sig.initSign(privateKeyEncrypt); sig.update(clientChallenge); byte[] signedBytes = sig.sign(); dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); // DataSerializer.writeString(privateKeyAlias, dos); DataSerializer.writeString(privateKeySubject, dos); DataSerializer.writeByteArray(signedBytes, dos); securityLogWriter.fine("HandShake: sent the signed client challenge"); } else { // These two lines should not be moved before the if{} statement in // a common block for both if...then...else parts. This is to handle // the case when an AuthenticationFailedException is thrown by the // if...then part when sending the signature. dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); } // Now send the server challenge DataSerializer.writeByteArray(challenge, dos); securityLogWriter.fine("HandShake: sent the public key and challenge"); dos.flush(); // Read and decrypt the credentials byte[] encBytes = DataSerializer.readByteArray(dis); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(dhPrivateKey); ka.doPhase(pubKey, true); Cipher decrypt; int keysize = getKeySize(skAlgo); int blocksize = getBlockSize(skAlgo); if (keysize == -1 || blocksize == -1) { SecretKey sKey = ka.generateSecret(skAlgo); decrypt = Cipher.getInstance(skAlgo); decrypt.init(Cipher.DECRYPT_MODE, sKey); } else { String algoStr = getDhAlgoStr(skAlgo); byte[] sKeyBytes = ka.generateSecret(); SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr); IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize); decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, sks, ivps); } byte[] credentialBytes = decrypt.doFinal(encBytes); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); credentials = DataSerializer.readProperties(dinp); byte[] challengeRes = DataSerializer.readByteArray(dinp); // Check the challenge string if (!Arrays.equals(challenge, challengeRes)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT .toLocalizedString()); } dinp.close(); } else { if (sendAuthentication) { // Read and ignore the client challenge DataSerializer.readByteArray(dis); } dos.writeByte(REPLY_AUTH_NOT_REQUIRED); dos.flush(); } } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) { // hitesh there will be no credential CCP will get credential(Principal) using // ServerConnection.. logger.debug("readCredential where multiuser mode creating callback connection"); } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex); } return credentials; }
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 {// w w w. j a va2 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"); 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 {// ww w . j a 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"); 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: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 w w. j a va 2 s .com 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); } }
From source file:tv.ouya.sdk.UnityOuyaFacade.java
public UnityOuyaFacade(Context context, Bundle savedInstanceState, String developerId, byte[] applicationKey) { try {/*from w w w. j av a2 s . c o m*/ this.context = context; Log.i(LOG_TAG, "UnityOuyaFacade.Init(" + developerId + ");"); UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "UnityOuyaFacade.Init(" + developerId + ");"); ouyaFacade = OuyaFacade.getInstance(); Init(developerId); // Create a PublicKey object from the key data downloaded from the developer portal. try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); mPublicKey = keyFactory.generatePublic(keySpec); } catch (Exception e) { Log.e(LOG_TAG, "Unable to create encryption key", e); } } catch (Exception ex) { Log.e(LOG_TAG, "UnityOuyaFacade constructor exception", ex); } }
From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java
public void setEncodedClientPublicKey(byte encoded[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encoded); KeyFactory kf = KeyFactory.getInstance("RSA"); clientPublicKey = kf.generatePublic(x509KeySpec); }