List of usage examples for java.security KeyFactory getInstance
public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:edu.internet2.middleware.openid.message.encoding.EncodingUtils.java
/** * Decode a DH private key.// w w w. j ava 2s . co m * * @param encodedKey private key to decode * @param parameters DH parameters used in decoding * @return decoded private key * @throws NoSuchAlgorithmException if DH algorithm is unavailable * @throws InvalidKeySpecException if unable to build a valid DH key spec */ public static DHPrivateKey decodePrivateKey(String encodedKey, DHParameterSpec parameters) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyBytes = Base64.decodeBase64(encodedKey.getBytes()); DHPrivateKeySpec keySpec = new DHPrivateKeySpec(new BigInteger(keyBytes), parameters.getP(), parameters.getG()); KeyFactory keyFactory = KeyFactory.getInstance("DH"); return (DHPrivateKey) keyFactory.generatePrivate(keySpec); }
From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JsonObjectWithDefault permissions) throws APIException { if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) { throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'"); }/*from w ww. j a v a2 s .com*/ JSONObject result = new JSONObject(); // return algorithm parameters and users for whom we are allowed to register a key if (post.get("getParameters", false)) { result.put("self", permissions.getBoolean("self", false)); result.put("users", permissions.getJSONObject("users")); result.put("userRoles", permissions.getJSONObject("userRoles")); JSONObject algorithms = new JSONObject(); JSONObject rsa = new JSONObject(); JSONArray keySizes = new JSONArray(); for (int i : allowedKeySizesRSA) { keySizes.put(i); } rsa.put("sizes", keySizes); rsa.put("defaultSize", defaultKeySizeRSA); algorithms.put("RSA", rsa); result.put("algorithms", algorithms); JSONArray formats = new JSONArray(); for (String format : allowedFormats) { formats.put(format); } result.put("formats", formats); return result; } // for which id? String id; if (post.get("id", null) != null) id = post.get("id", null); else id = authorization.getIdentity().getName(); // check if we are allowed register a key if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user // create Authentication to check if the user id is a registered user ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id); Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); throw new APIException(400, "Bad request"); // do not leak if user exists or not } // check if the current user is allowed to create a key for the user in question boolean allowed = false; // check if the user in question is in 'users' if (permissions.getJSONObject("users", null).has(id) && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) { allowed = true; } else { // check if the user role of the user in question is in 'userRoles' Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization, DAO.userRoles); for (String key : permissions.getJSONObject("userRoles").keySet()) { if (key.equals(auth.getUserRole().getName()) && permissions.getJSONObject("userRoles").getBoolean(key)) { allowed = true; } } } if (!allowed) throw new APIException(400, "Bad request"); // do not leak if user exists or not } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users) if (!permissions.getBoolean("self", false)) throw new APIException(403, "You are not allowed to register a public key"); } // set algorithm. later, we maybe want to support other algorithms as well String algorithm = "RSA"; if (post.get("algorithm", null) != null) { algorithm = post.get("algorithm", null); } if (post.get("create", false)) { // create a new key pair on the server if (algorithm.equals("RSA")) { int keySize = 2048; if (post.get("key-size", null) != null) { int finalKeyLength = post.get("key-size", 0); if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) { throw new APIException(400, "Invalid key size."); } keySize = finalKeyLength; } KeyPairGenerator keyGen; KeyPair keyPair; try { keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(keySize); keyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new APIException(500, "Server error"); } registerKey(authorization.getIdentity(), keyPair.getPublic()); String pubkey_pem = null, privkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); pemWriter.flush(); pemWriter.close(); privkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); result.put("privatekey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("privatekey_PEM", privkey_pem); result.put("keyhash", IO.getKeyHash(keyPair.getPublic())); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("key-size", keySize); result.put("message", "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server"); return result; } throw new APIException(400, "Unsupported algorithm"); } else if (post.get("register", null) != null) { if (algorithm.equals("RSA")) { String type = post.get("type", null); if (type == null) type = "DER"; RSAPublicKey pub; String encodedKey; try { encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8"); } catch (Throwable e) { throw new APIException(500, "Server error"); } Log.getLog().info("Key (" + type + "): " + encodedKey); if (type.equals("DER")) { try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey)); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Throwable e) { throw new APIException(400, "Public key not readable (DER)"); } } else if (type.equals("PEM")) { try { PemReader pemReader = new PemReader(new StringReader(encodedKey)); PemObject pem = pemReader.readPemObject(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent()); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Exception e) { throw new APIException(400, "Public key not readable (PEM)"); } } else { throw new APIException(400, "Invalid value for 'type'."); } // check key size (not really perfect yet) int keySize; int bitLength = pub.getModulus().bitLength(); if (bitLength <= 512) { keySize = 512; } else if (bitLength <= 1024) { keySize = 1024; } else if (bitLength <= 2048) { keySize = 2048; } else if (bitLength <= 4096) { keySize = 4096; } else { keySize = 8192; } if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) { throw new APIException(400, "Invalid key length."); } registerKey(authorization.getIdentity(), pub); String pubkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("keyhash", IO.getKeyHash(pub)); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("message", "Successfully registered key."); return result; } throw new APIException(400, "Unsupported algorithm"); } throw new APIException(400, "Invalid parameter"); }
From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) { throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'"); }/*from ww w . jav a2s. c o m*/ JSONObject result = new JSONObject(); // return algorithm parameters and users for whom we are allowed to register a key if (post.get("getParameters", false)) { result.put("self", permissions.getBoolean("self", false)); result.put("users", permissions.getJSONObject("users")); result.put("userRoles", permissions.getJSONObject("userRoles")); JSONObject algorithms = new JSONObject(); JSONObject rsa = new JSONObject(); JSONArray keySizes = new JSONArray(); for (int i : allowedKeySizesRSA) { keySizes.put(i); } rsa.put("sizes", keySizes); rsa.put("defaultSize", defaultKeySizeRSA); algorithms.put("RSA", rsa); result.put("algorithms", algorithms); JSONArray formats = new JSONArray(); for (String format : allowedFormats) { formats.put(format); } result.put("formats", formats); return result; } // for which id? String id; if (post.get("id", null) != null) id = post.get("id", null); else id = authorization.getIdentity().getName(); // check if we are allowed register a key if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user // create Authentication to check if the user id is a registered user ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id); Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); throw new APIException(400, "Bad request"); // do not leak if user exists or not } // check if the current user is allowed to create a key for the user in question boolean allowed = false; // check if the user in question is in 'users' if (permissions.getJSONObject("users", null).has(id) && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) { allowed = true; } else { // check if the user role of the user in question is in 'userRoles' Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization, DAO.userRoles); for (String key : permissions.getJSONObject("userRoles").keySet()) { if (key.equals(auth.getUserRole().getName()) && permissions.getJSONObject("userRoles").getBoolean(key)) { allowed = true; } } } if (!allowed) throw new APIException(400, "Bad request"); // do not leak if user exists or not } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users) if (!permissions.getBoolean("self", false)) throw new APIException(403, "You are not allowed to register a public key"); } // set algorithm. later, we maybe want to support other algorithms as well String algorithm = "RSA"; if (post.get("algorithm", null) != null) { algorithm = post.get("algorithm", null); } if (post.get("create", false)) { // create a new key pair on the server if (algorithm.equals("RSA")) { int keySize = 2048; if (post.get("key-size", null) != null) { int finalKeyLength = post.get("key-size", 0); if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) { throw new APIException(400, "Invalid key size."); } keySize = finalKeyLength; } KeyPairGenerator keyGen; KeyPair keyPair; try { keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(keySize); keyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new APIException(500, "Server error"); } registerKey(authorization.getIdentity(), keyPair.getPublic()); String pubkey_pem = null, privkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); pemWriter.flush(); pemWriter.close(); privkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); result.put("privatekey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("privatekey_PEM", privkey_pem); result.put("keyhash", IO.getKeyHash(keyPair.getPublic())); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("key-size", keySize); result.put("message", "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server"); return result; } throw new APIException(400, "Unsupported algorithm"); } else if (post.get("register", null) != null) { if (algorithm.equals("RSA")) { String type = post.get("type", null); if (type == null) type = "DER"; RSAPublicKey pub; String encodedKey; try { encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8"); } catch (Throwable e) { throw new APIException(500, "Server error"); } Log.getLog().info("Key (" + type + "): " + encodedKey); if (type.equals("DER")) { try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey)); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Throwable e) { throw new APIException(400, "Public key not readable (DER)"); } } else if (type.equals("PEM")) { try { PemReader pemReader = new PemReader(new StringReader(encodedKey)); PemObject pem = pemReader.readPemObject(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent()); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Exception e) { throw new APIException(400, "Public key not readable (PEM)"); } } else { throw new APIException(400, "Invalid value for 'type'."); } // check key size (not really perfect yet) int keySize; int bitLength = pub.getModulus().bitLength(); if (bitLength <= 512) { keySize = 512; } else if (bitLength <= 1024) { keySize = 1024; } else if (bitLength <= 2048) { keySize = 2048; } else if (bitLength <= 4096) { keySize = 4096; } else { keySize = 8192; } if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) { throw new APIException(400, "Invalid key length."); } registerKey(authorization.getIdentity(), pub); String pubkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("keyhash", IO.getKeyHash(pub)); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("message", "Successfully registered key."); return result; } throw new APIException(400, "Unsupported algorithm"); } throw new APIException(400, "Invalid parameter"); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
private void encryptAndWriteAESKey(SecretKey aeskey, File dest) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { Cipher keyc;//from w ww .j av a 2 s .com AssetManager am = getAssets(); InputStream in = am.open("mouflon_key.pub"); byte[] readFromFile = new byte[in.available()]; //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value in.read(readFromFile); keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something. KeyFactory kf = KeyFactory.getInstance("RSA"); KeySpec ks = new X509EncodedKeySpec(readFromFile); RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks); keyc.init(Cipher.ENCRYPT_MODE, key); //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded()); FileOutputStream out = new FileOutputStream(dest); CipherOutputStream outcipher = new CipherOutputStream(out, keyc); outcipher.write(aeskey.getEncoded()); outcipher.close(); out.close(); }
From source file:com.owncloud.android.utils.PushUtils.java
public static Key readKeyFromFile(boolean readPublicKey) { String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;// ww w .j a v a 2 s . c om String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION; String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION; String path; if (readPublicKey) { path = publicKeyPath; } else { path = privateKeyPath; } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(path); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); fileInputStream.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); if (readPublicKey) { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); return keyFactory.generatePublic(keySpec); } else { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); return keyFactory.generatePrivate(keySpec); } } catch (FileNotFoundException e) { Log_OC.d(TAG, "Failed to find path while reading the Key"); } catch (IOException e) { Log_OC.d(TAG, "IOException while reading the key"); } catch (InvalidKeySpecException e) { Log_OC.d(TAG, "InvalidKeySpecException while reading the key"); } catch (NoSuchAlgorithmException e) { Log_OC.d(TAG, "RSA algorithm not supported"); } return null; }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private void generateCertificateSigningRequest(Integer infrastructureId, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try {/*from w w w . ja va2 s . c o m*/ InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); InfrastructureDataObject infrastructure = dao.getInfrastructure(infrastructureId); String CN = infrastructure.getCommonName(); String OU = infrastructure.getOrganizationalUnit(); String O = infrastructure.getOrganization(); String L = infrastructure.getLocality(); String S = infrastructure.getState(); String C = infrastructure.getCountry(); Base64 base64 = new Base64(); byte[] pubKey = base64.decode(infrastructure.getBase64EncodedPublicKey()); byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey()); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pubKey)); PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey)); CertificateIdentifier principal = new CertificateIdentifier(CN, OU, O, L, S, C); PKCS10CertificationRequest request = SslUtility.generatePKCS10(publicKey, privateKey, principal); String csr = SslUtility.generateCSR(request); out.println(csr); } catch (NumberFormatException e) { out.println(e); } catch (InvalidKeySpecException e) { out.println(e); } catch (NoSuchAlgorithmException e) { out.println(e); } catch (SslException e) { out.println(e); } }
From source file:jef.tools.security.EncrypterUtil.java
/** * x509/*from w w w . j av a2 s .c om*/ * * @param f * @param algom * ? getSupportedAlgorithmName (AlgorithmType.KeyFactory) * @param isPublic * true?false?? * @return */ public static Key loadX509Key(File f, String algom, boolean isPublic) { try { byte[] keyData = IOUtils.toByteArray(f); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData); KeyFactory keyFactory = KeyFactory.getInstance(algom); Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec); return result; } catch (IOException e) { throw new RuntimeException(e); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Reads a PKCS8 formatted private key from file. * // w w w. j ava 2s .c o m * @param in the <code>InputStream</code> containing the key * @param alg the key algorithm * @return the read key * @throws Exception if error occurs reading the key */ public static PrivateKey readPKCS8(InputStream in, String alg) throws Exception { try { if (alg == null) throw new NullPointerException("alg"); //alg = alg.toUpperCase(); //if(!alg.equals("DSA") || !alg.equals("RSA")) // throw new IllegalArgumentException("Illegal key alg=" + alg); byte[] encodedKey = ByteUtils.readBytes(in); KeyFactory kf = KeyFactory.getInstance(alg); try { return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey)); } catch (Exception e) { // maybe key was in PEM so convert to binary encodedKey = EncryptUtils.fromPemtoBinary(encodedKey); return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey)); } } finally { MiscUtils.closeStream(in); } }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitivesTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { config = Config.getConfig();//from w w w. j a v a2 s.c o m plainText = DatatypeConverter.parseHexBinary(PLAIN_TEXT_HEX); sig = DatatypeConverter.parseHexBinary(SIGNATURE_HEX); pemCert = DatatypeConverter.parseHexBinary(PEM_CERT_HEX); invalidPemCert = DatatypeConverter.parseHexBinary(INVALID_PEM_CERT); kf = KeyFactory.getInstance("EC"); cf = CertificateFactory.getInstance("X.509"); crypto = new CryptoPrimitives(); crypto.init(); }
From source file:com.wso2telco.gsma.authenticators.OpCoCompositeAuthenticator.java
/** * Read public key from file./* w ww.j a v a2s .com*/ * * @param fileName the file name * @return the public key * @throws AuthenticationFailedException the authentication failed exception */ private PublicKey readPublicKeyFromFile(String fileName) throws AuthenticationFailedException { try { String publicK = readStringKey(fileName); byte[] keyBytes = Base64.decodeBase64(publicK.getBytes()); ; X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(spec); } catch (Exception e) { throw new AuthenticationFailedException( "Authentication Failed since reading public key from file failed."); } }