List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
static PrivateKey loadPrivateKey(String file, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Private Key. File filePrivateKey = new File(file); FileInputStream fis = new FileInputStream(file); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey);//from w w w . j a v a 2 s.c o m fis.close(); // Generate KeyPair. KeyFactory keyFactory = KeyFactory.getInstance(algorithm); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; }
From source file:org.bedework.util.security.pki.PKITools.java
private PrivateKey makePrivateKey(final byte[] privKeyBytes) throws PKIException { try {//from w ww . j ava2 s. c o m PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); KeyFactory kf; if (curSchema.pName == null) { kf = KeyFactory.getInstance(curSchema.algorithm); } else { kf = KeyFactory.getInstance(curSchema.algorithm, curSchema.pName); } return kf.generatePrivate(privateKeySpec); } catch (Throwable t) { throw new PKIException(t); } }
From source file:net.jmhertlein.core.crypto.Keys.java
/** * Given a Base64-encoded, PKCS8-formatted RSA private key, returns a PrivateKey object representing it * * @param encodedKey/* w w w . j av a 2s .com*/ * * @return the RSA private key, or null if the RSA algorithm is not available on the system */ public static PrivateKey getPrivateKeyFromBASE64PKCS8Encoded(String encodedKey) { byte[] decoded = Base64.decodeBase64(encodedKey); try { return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
private void savePrivateKey(String file, PrivateKey privateKey) throws IOException { // Store Private Key. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); FileOutputStream fos = new FileOutputStream(file); fos.write(pkcs8EncodedKeySpec.getEncoded()); fos.close();//from ww w .j a v a 2s .c om }
From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java
private static PrivateKey createKey() throws Exception { byte[] derKey = Base64.decode(TEST_KEY.getBytes(), Base64.DEFAULT); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(derKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
From source file:authorize.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger logger = LogManager.getLogger(authorize.class); logger.trace("START"); PrintWriter out = response.getWriter(); Connection conn = null;//w w w . ja va 2 s .co m Statement stmt = null; ResultSet rs = null; HttpSession session = request.getSession(false); String response_type = request.getParameter("response_type"); String username = request.getParameter("username"); String password = request.getParameter("password"); String prompt = request.getParameter("prompt"); String login_hint = request.getParameter("login_hint"); String max_age = request.getParameter("max_age"); String client_id = request.getParameter("client_id"); String redirect_uri = request.getParameter("redirect_uri"); String scope = request.getParameter("scope"); String state = request.getParameter("state"); String nonce = request.getParameter("nonce"); String consent = request.getParameter("consent"); String client_scope = null; String access_token = null; String id_token = null; String passwd = null; String db_redirect_uri = null; String path = null; String sql = null; String uri = null; String issuer = null; String keyname = null; String kit = "public.key"; boolean redirect_uri_check = true; int access_token_time = 60; if (scope == null) { scope = "openid"; } else if (scope.equals("consent")) { scope = null; if (null != request.getParameter("openid")) { scope = "openid"; if (null != request.getParameter("profile")) scope += " profile"; if (null != request.getParameter("email")) scope += " email"; if (null != request.getParameter("phone")) scope += " phone"; if (null != request.getParameter("address")) scope += " address"; } } logger.trace(scope); if (prompt != null && prompt.contains("login") && consent == null && session != null) session.invalidate(); try { ServletContext context = this.getServletContext(); path = context.getRealPath("/WEB-INF/oauth2"); Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); conn = DriverManager.getConnection("jdbc:derby:" + path); stmt = conn.createStatement(); logger.trace("connect()"); sql = "SELECT scope,redirect_uri FROM client WHERE client_id='" + client_id + "'"; rs = stmt.executeQuery(sql); while (rs.next()) { client_scope = rs.getString("scope"); db_redirect_uri = rs.getString("redirect_uri"); } logger.trace(sql); if (redirect_uri == null) redirect_uri = db_redirect_uri; sql = "SELECT passwd FROM profile WHERE uid='" + username + "'"; rs = stmt.executeQuery(sql); while (rs.next()) { passwd = rs.getString("passwd"); } logger.trace(sql); path = context.getRealPath("/WEB-INF/config.json"); InputStream input = new FileInputStream(path); JsonParser parser = Json.createParser(input); while (parser.hasNext()) { JsonParser.Event event = parser.next(); switch (event) { case KEY_NAME: keyname = parser.getString(); break; case VALUE_NUMBER: access_token_time = parser.getInt(); break; case VALUE_TRUE: redirect_uri_check = true; break; case VALUE_FALSE: redirect_uri_check = false; break; case VALUE_STRING: if (keyname.equals("issuer")) issuer = parser.getString(); if (keyname.equals("kit")) kit = parser.getString(); break; default: break; } } java.util.Date dt = new java.util.Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); if (client_scope != null && passwd != null) { byte[] cipher_byte; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); cipher_byte = md.digest(); String sha256_password = Base64.getEncoder().withoutPadding().encodeToString(cipher_byte); StringTokenizer strToken = new StringTokenizer(scope, " "); while (strToken.hasMoreTokens()) { String token = strToken.nextToken().toString(); logger.trace(token); if (!client_scope.contains(token)) throw new Exception("out of scope"); } if (passwd.contains(sha256_password) && (!redirect_uri_check || db_redirect_uri.equals(redirect_uri))) { if (prompt != null && prompt.contains("consent") && !consent.equals("false")) { username = "null"; password = "null"; consent = "true"; throw new Exception("consent is true"); } access_token = RandomStringUtils.randomAlphanumeric(32); logger.trace(access_token); sql = "insert into session(uid,access_token,issued_in,scope,client_id) values ('" + username + "','" + access_token + "','" + currentTime + "','" + scope + "','" + client_id + "')"; stmt.executeUpdate(sql); md.update(access_token.getBytes()); cipher_byte = md.digest(); byte[] half_cipher_byte = Arrays.copyOf(cipher_byte, (cipher_byte.length / 2)); String at_hash = Base64.getEncoder().withoutPadding().encodeToString(half_cipher_byte); path = context.getRealPath("/WEB-INF/private.der"); File filePrivateKey = new File(path); FileInputStream fis = new FileInputStream(path); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); fis.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); Calendar exp = Calendar.getInstance(); exp.add(Calendar.SECOND, access_token_time); if (nonce == null || nonce.equals("null")) { if (response_type.contains("id_token")) { uri = redirect_uri; uri += "#error=invalid_request&error_description=nonce%20is%20not%20valid."; response.sendRedirect(uri); logger.info(uri); return; } } else { id_token = Jwts.builder().setHeaderParam("alg", "RS256").setHeaderParam("typ", "JWT") .setHeaderParam("kid", kit).setIssuer(issuer).claim("at_hash", at_hash) .setSubject(username).setAudience(client_id).claim("nonce", nonce) .setSubject(username).setExpiration(exp.getTime()) .setIssuedAt(Calendar.getInstance().getTime()) .claim("auth_time", String.valueOf(Calendar.getInstance().getTime().getTime()).substring(0, 10)) .signWith(SignatureAlgorithm.RS256, privateKey).compact(); logger.trace(id_token); } uri = redirect_uri; if (response_type.equals("token")) uri += "#access_token=" + access_token + "&token_type=bearer&expires_in=" + access_token_time; if (response_type.equals("id_token")) uri += "#id_token=" + id_token; if (response_type.equals("token id_token") || response_type.equals("id_token token")) uri += "#access_token=" + access_token + "&token_type=bearer&expires_in=" + access_token_time + "&id_token=" + id_token; if (state != null && !state.equals("null")) uri += "&state=" + state; response.sendRedirect(uri); logger.info(uri); return; } } } catch (Exception e) { logger.trace(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); logger.trace("close()"); } catch (SQLException e) { logger.trace(e.getMessage()); } } if (redirect_uri != null || redirect_uri.equals("null")) uri = redirect_uri; else uri = "/myop/error"; if (username != null && !username.equals("null") && password != null && !password.equals("null")) { uri += "#error=access_denied&error_description=User%20authentication%20failed."; session = request.getSession(false); if (session != null) session.invalidate(); } else if (scope == null) { uri += "#error=invalid_scope&error_description=The%20scope%20value%20is%20not%20supported."; } else if (client_scope == null || client_scope.equals("null")) { uri += "#error=unauthorized_clienti&error_description=Client%20authentication%20failed."; } else if (response_type == null || response_type.equals("null") || !(response_type.equals("token") || response_type.equals("id_token") || response_type.equals("token id_token") || response_type.equals("id_token token"))) { uri += "#error=unsupported_response_type&error_description==The%20response_type%20value%20%22" + response_type + "%22%20is%20not%20supported."; } else if (redirect_uri_check && !db_redirect_uri.equals(redirect_uri)) { uri += "#error=invalid_request&error_description=redirect_uri%20is%20not%20valid."; } else { uri = "/myop/login?response_type=" + URLEncoder.encode(response_type, "UTF-8") + "&client_id=" + client_id + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&scope=" + URLEncoder.encode(scope, "UTF-8"); if (nonce != null && !nonce.equals("null")) uri += "&nonce=" + nonce; if (prompt != null && !prompt.equals("null")) uri += "&prompt=" + prompt; if (login_hint != null && !login_hint.equals("null")) uri += "&login_hint=" + login_hint; if (max_age != null && !max_age.equals("null")) uri += "&max_age=" + max_age; if (consent != null && consent.equals("true")) uri += "&consent=" + consent; } if (state != null && !state.equals("null")) uri += "&state=" + state; response.sendRedirect(uri); logger.info(uri); logger.trace("END"); }
From source file:oscar.oscarLab.ca.all.pageUtil.LabUploadAction.java
private static PrivateKey getServerPrivate() { PrivateKey Key = null; Base64 base64 = new Base64(0); byte[] privateKey; try {/*from w ww . j av a 2 s .c om*/ OscarKeyDao oscarKeyDao = (OscarKeyDao) SpringUtils.getBean("oscarKeyDao"); OscarKey oscarKey = oscarKeyDao.find("oscar"); logger.info("oscar key: " + oscarKey); privateKey = base64.decode(oscarKey.getPrivateKey().getBytes(MiscUtils.ENCODING)); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key = keyFactory.generatePrivate(privKeySpec); } catch (Exception e) { logger.error("Could not retrieve private key: ", e); } return (Key); }
From source file:org.ow2.proactive.authentication.crypto.Credentials.java
/** * Retrieves a private key stored in a local file * <p>// w w w . j a va 2 s. com * Tries to guess the algorithm used for keypair generation which * is not included in the file. According to <a href="http://download.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA">Java Cryptography Specification</a>, * the algorithm can be only one of "RSA" or "DSA", so we can just try both using the * <code>algorithms</code> param. If the algorithm used to generate the key is neither RSA or DSA * (highly unlikely), this method cannot recreate the private key, but {@link #decrypt(String)} * maybe will. * * @param privPath * path to the private key on the local filesystem * @param algorithms a list of algorithms to try for creating the PK. Recommanded value: * {"RSA","DSA"} * @return the key encapsulated in a regular JCE container * @throws KeyException * the key could not be retrieved or is malformed, or the algorithm used for generation * is not one of <code>algorithms</code> */ public static PrivateKey getPrivateKey(String privPath, String[] algorithms) throws KeyException { PrivateKey privKey = null; for (String algo : algorithms) { try { KeyFactory keyFactory; keyFactory = KeyFactory.getInstance(algo); // recover private key bytes byte[] bytes; try { File pkFile = new File(privPath); DataInputStream pkStream = new DataInputStream(new FileInputStream(pkFile)); bytes = new byte[(int) pkFile.length()]; pkStream.readFully(bytes); pkStream.close(); } catch (Exception e) { throw new KeyException("Could not recover private key (algo=" + algo + ")", e); } // reconstruct private key PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(bytes); try { privKey = keyFactory.generatePrivate(privKeySpec); } catch (InvalidKeySpecException e) { throw new KeyException("Cannot re-generate private key (algo=" + algo + ")", e); } } catch (Exception e) { } } if (privKey == null) { String str = "Could not generate Private Key (algorithms: "; for (String algo : algorithms) { str += algo + " "; } str += ")"; throw new KeyException(str); } return privKey; }
From source file:org.codice.ddf.security.certificate.generator.PkiTools.java
/** * Convert a Java String to an private key * * @param keyString encoded RSA private key. Assume PKCS#8 format * @return Instance of PrivateKey//w w w . j a v a2 s . c o m */ public static PrivateKey pemToPrivateKey(String keyString) { try { return PkiTools.getRsaKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(pemToDer(keyString))); } catch (Exception e) { throw new CertificateGeneratorException("Could not convert String to Private Key", e.getCause()); } }