List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String) *//*from ww w .ja va 2 s . c om*/ public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#returnKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } KeyPair keyPair = null; InputStream pubStream = null; InputStream privStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { throw new KeyManagementException("Configured key directory does not exist and unable to create it"); } File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if ((publicFile.exists()) && (privateFile.exists())) { privStream = new FileInputStream(privateFile); byte[] privKeyBytes = IOUtils.toByteArray(privStream); pubStream = new FileInputStream(publicFile); byte[] pubKeyBytes = IOUtils.toByteArray(pubStream); // files exist KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm()); // generate private key PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes); PrivateKey privKey = keyFactory.generatePrivate(privateSpec); // generate pubkey X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(publicSpec); // make the keypair keyPair = new KeyPair(pubKey, privKey); } else { // files dont exist throw new KeyManagementException("Failed to locate user keys"); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (InvalidKeySpecException iksx) { throw new KeyManagementException(iksx.getMessage(), iksx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (privStream != null) { IOUtils.closeQuietly(privStream); } if (pubStream != null) { IOUtils.closeQuietly(pubStream); } } return keyPair; }
From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.java
@Override public void install(final PurchaseObserver observer, PurchaseManagerConfig config) { this.observer = observer; this.config = config; // Obtain applicationKey and developer ID. Pass in as follows: // ------------------------------------------------------------------------- // config.addStoreParam( // PurchaseManagerConfig.STORE_NAME_ANDROID_OUYA, // new Object[] { OUYA_DEVELOPERID_STRING, applicationKeyPathSTRING }); // ------------------------------------------------------------------------- Object[] configuration = (Object[]) config.getStoreParam(PurchaseManagerConfig.STORE_NAME_ANDROID_OUYA); String developerID = (String) configuration[0]; applicationKeyPath = (String) configuration[1]; // store our OUYA applicationKey-Path! ouyaFacade = OuyaFacade.getInstance(); ouyaFacade.init((Context) activity, developerID); // --- copy all available products to the list of purchasables productIDList = new ArrayList<Purchasable>(config.getOfferCount()); for (int i = 0; i < config.getOfferCount(); i++) { productIDList.add(new Purchasable(config.getOffer(i).getIdentifier())); }//from ww w. j ava 2s. c o m // Create a PublicKey object from the key data downloaded from the developer portal. try { // Read in the key.der file (downloaded from the developer portal) FileHandle fHandle = Gdx.files.internal(applicationKeyPath); byte[] applicationKey = fHandle.readBytes(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); ouyaPublicKey = keyFactory.generatePublic(keySpec); showMessage(LOGTYPELOG, "succesfully created publicKey"); // ---- request the productlist --------- requestProductList(); // notify of successful initialization observer.handleInstall(); } catch (Exception e) { // notify about the problem showMessage(LOGTYPEERROR, "Problem setting up in-app billing: Unable to create encryption key"); observer.handleInstallError(new RuntimeException( "Problem setting up in-app billing: Unable to create encryption key: " + e)); } }
From source file:org.gluu.oxtrust.action.ManageCertificateAction.java
private KeyPair getKeyPair(String fileName) { KeyPair pair = null;/*from w w w . ja v a2 s .c om*/ JCERSAPrivateCrtKey privateKey = null; PEMReader r = null; FileReader fileReader = null; File keyFile = new File(getTempCertDir() + fileName.replace("crt", "key")); if (keyFile.isFile()) { try { fileReader = new FileReader(keyFile); r = new PEMReader(fileReader, new PasswordFinder() { public char[] getPassword() { // Since keys are stored without a password this // function should not be called. return null; } }); Object keys = r.readObject(); if (keys == null) { log.error(" Unable to read keys from: " + keyFile.getAbsolutePath()); return null; } if (keys instanceof KeyPair) { pair = (KeyPair) keys; log.debug(keyFile.getAbsolutePath() + "contains KeyPair"); } else if (keys instanceof JCERSAPrivateCrtKey) { privateKey = (JCERSAPrivateCrtKey) keys; log.debug(keyFile.getAbsolutePath() + "contains JCERSAPrivateCrtKey"); BigInteger exponent = privateKey.getPublicExponent(); BigInteger modulus = privateKey.getModulus(); RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent); PublicKey publicKey = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { e.printStackTrace(); } pair = new KeyPair(publicKey, privateKey); } else { log.error(keyFile.getAbsolutePath() + " Contains unsupported key type: " + keys.getClass().getName()); return null; } } catch (IOException e) { log.error(e.getMessage(), e); return null; } finally { try { r.close(); fileReader.close(); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } } else { log.error("Key file does not exist : " + keyFile.getAbsolutePath()); } log.debug("KeyPair successfully extracted from: " + keyFile.getAbsolutePath()); return pair; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * An ECDSA key can be stripped of the curve parameters so it only contains the public point, and this is not enough to use the key for * verification. However, if we know the curve name we can fill in the curve parameters and get a usable EC public key * //from w w w .j a v a 2s .c o m * @param pk * PublicKey, org.ejbca.cvc.PublicKeyEC, that might miss parameters, if parameters are there we do not touch the public key just return it unchanged * @param pkwithparams * PublicKey, org.ejbca.cvc.PublicKeyEC, that contains all parameters. * @return PublicKey with parameters from the named curve * * @throws InvalidKeySpecException if the key specification in pkwithparams was invalid */ public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams) throws InvalidKeySpecException { PublicKey ret = pk; if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) { final PublicKeyEC pkec = (PublicKeyEC) pk; // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key final ECParameterSpec spec = pkec.getParams(); if (spec == null) { final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams; final ECParameterSpec pkspec = pkecp.getParams(); if (pkspec != null) { final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false); final java.security.spec.ECPoint p = pkec.getW(); final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false); final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec); KeyFactory keyfact; try { keyfact = KeyFactory.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECDSA was an unknown algorithm", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } ret = keyfact.generatePublic(pubKey); } else { log.info("pkwithparams does not have any params."); } } } else { log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", " + pkwithparams.toString()); } return ret; }
From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mOuyaFacade = OuyaFacade.getInstance(); Bundle developerInfo = new Bundle(); developerInfo.putString(OuyaFacade.OUYA_DEVELOPER_ID, DEVELOPER_ID); developerInfo.putByteArray(OuyaFacade.OUYA_DEVELOPER_PUBLIC_KEY, loadApplicationKey()); mOuyaFacade = OuyaFacade.getInstance(); mOuyaFacade.init(this, developerInfo); // 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); /*// w ww . j ava 2 s. co 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) { fetchGamerInfo(); } }); // 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(loadApplicationKey()); 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:cn.quickj.AbstractApplication.java
private void decryptQuickjLicense(String hex) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encrypted = Hex.decodeHex(hex.toCharArray()); byte[] keydata = new byte[128]; System.arraycopy(encrypted, 0, keydata, 0, 128); String key = new String(Hex.encodeHex(keydata)); PublicKey pubKey = keyFactory .generatePublic(new RSAPublicKeySpec(new BigInteger(key, 16), new BigInteger("10001", 16))); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, pubKey); byte[] decrypted = new byte[encrypted.length]; int outputOffset = 0; for (int offset = 128; offset < encrypted.length;) { int inputLen = (encrypted.length - offset) > 128 ? 128 : (encrypted.length - offset); outputOffset += cipher.doFinal(encrypted, offset, inputLen, decrypted, outputOffset); offset += inputLen;/*from w w w. j a va 2 s . c o m*/ } String licenseInfo = new String(decrypted, 0, outputOffset - 16, "utf8"); String[] s = licenseInfo.split("\\|"); hosts = s[1].split(","); endDate = new SimpleDateFormat("yyyy-MM-dd").parse(s[2]); byte[] md5 = new byte[16]; System.arraycopy(decrypted, outputOffset - 16, md5, 0, 16); licensePath = new String(Hex.encodeHex(md5)); }
From source file:io.cslinmiso.line.api.impl.LineApiImpl.java
public LoginResult login(String id, String password, String certificate) throws Exception { IdentityProvider provider = null;//from w w w .j a va 2s . com Map<String, String> json = null; String sessionKey = null; boolean keepLoggedIn = true; String accessLocation = this.ip; // Login to LINE server. if (id.matches(EMAIL_REGEX)) { provider = IdentityProvider.LINE; // LINE json = getCertResult(LINE_SESSION_LINE_URL); } else { provider = IdentityProvider.NAVER_KR; // NAVER json = getCertResult(LINE_SESSION_NAVER_URL); } if (id != null) { this.id = id; } if (password != null) { this.password = password; } if (StringUtils.isNotEmpty(certificate)) { setCertificate(certificate); } else { // read the certificate file if it exists try { List<String> readFile = Utility.readFile(LineApiImpl.CERT_FILE); String tmpCert = readFile != null ? readFile.get(0) : ""; if (tmpCert != null) { setCertificate(tmpCert); } } catch (Exception ex) { setCertificate(""); } } sessionKey = json.get("session_key"); String tmpMsg = (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id + (char) (password.length()) + password; String message = new String(tmpMsg.getBytes(), java.nio.charset.StandardCharsets.UTF_8); String[] keyArr = json.get("rsa_key").split(","); String keyName = keyArr[0]; String n = keyArr[1]; String e = keyArr[2]; BigInteger modulus = new BigInteger(n, 16); BigInteger pubExp = new BigInteger(e, 16); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] enBytes = cipher.doFinal(message.getBytes()); String encryptString = Hex.encodeHexString(enBytes); THttpClient transport = new THttpClient(LINE_HTTP_URL); transport.setCustomHeaders(headers); transport.open(); TProtocol protocol = new TCompactProtocol(transport); this.client = new TalkService.Client(protocol); LoginResult result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString, keepLoggedIn, accessLocation, this.systemName, this.certificate); if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) { headers.put("X-Line-Access", result.getVerifier()); String pinCode = result.getPinCode(); System.out.printf("Enter PinCode '%s' to your mobile phone in 2 minutes.\n", pinCode); // await for pinCode to be certified, it will return a verifier afterward. loginWithVerifierForCertificate(); } else if (result.getType() == LoginResultType.SUCCESS) { // if param certificate has passed certification setAuthToken(result.getAuthToken()); } // Once the client passed the verification, switch connection to HTTP_IN_URL this.client = ready(); return result; }
From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java
public void setEncodedServerPublicKey(byte encoded[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encoded); KeyFactory kf = KeyFactory.getInstance("RSA"); serverPublicKey = kf.generatePublic(x509KeySpec); }
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); /*/* w w w. j a v a 2s.co 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.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarAddDeviceHtml.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */// w w w . j a v a 2 s . co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String S_ProcName = "doPost"; ICFAsteriskSchemaObj schemaObj; HttpSession sess = request.getSession(false); if (sess == null) { sess = request.getSession(true); schemaObj = new CFAsteriskSchemaPooledObj(); sess.setAttribute("SchemaObj", schemaObj); } else { schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj"); if (schemaObj == null) { response.sendRedirect("CFAsteriskSMWarLoginHtml"); return; } } CFSecurityAuthorization auth = schemaObj.getAuthorization(); if (auth == null) { response.sendRedirect("CFAsteriskSMWarLoginHtml"); return; } ICFSecuritySecUserObj secUser = null; ICFSecurityClusterObj secCluster = null; String clusterDescription = ""; ICFAsteriskSchema dbSchema = null; try { dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.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=\"CFAsteriskSMWarAddDeviceHtml\">"); 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='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } ICFSecuritySecDeviceObj 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=\"CFAsteriskSMWarAddDeviceHtml\">"); 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='CFAsteriskSMWarSecurityMainHtml'\">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=\"CFAsteriskSMWarAddDeviceHtml\">"); 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='CFAsteriskSMWarSecurityMainHtml'\">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=\"CFAsteriskSMWarAddDeviceHtml\">"); 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='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); return; } ICFSecurityClusterObj systemCluster = schemaObj.getClusterTableObj() .readClusterByUDomainNameIdx("system"); ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj() .readTenantByUNameIdx(systemCluster.getRequiredId(), "system"); ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system"); ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance(); ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession .beginEdit(); editSystemSession.setRequiredContainerSecUser(systemUser); editSystemSession.setRequiredStart(Calendar.getInstance()); systemSession = editSystemSession.create(); editSystemSession.endEdit(); CFSecurityAuthorization secAuth = new CFSecurityAuthorization(); secAuth.setSecCluster(systemCluster); secAuth.setSecTenant(systemTenant); secAuth.setSecSession(systemSession); schemaObj.setAuthorization(secAuth); secDev = schemaObj.getSecDeviceTableObj().newInstance(); ICFSecuritySecDeviceEditObj editDev = secDev.beginEdit(); editDev.setRequiredContainerSecUser(secUser); editDev.setRequiredDevName(deviceName); editDev.setOptionalPubKey(publicKey); secDev = editDev.create(); editDev.endEdit(); if (null == secUser.getOptionalLookupDefDev()) { ICFSecuritySecUserEditObj editSecUser = secUser.beginEdit(); editSecUser.setOptionalLookupDefDev(secDev); editSecUser.update(); editSecUser.endEdit(); } editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit(); editSystemSession.setOptionalFinish(Calendar.getInstance()); editSystemSession.update(); editSystemSession.endEdit(); schemaObj.commit(); schemaObj.setAuthorization(auth); response.sendRedirect("CFAsteriskSMWarSecurityMainHtml"); } 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=\"CFAsteriskSMWarAddDeviceHtml\">"); 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='CFAsteriskSMWarSecurityMainHtml'\">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); CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema); } } }