List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:org.slc.sli.bulk.extract.files.ExtractFileTest.java
/** * Runs before JUnit tests and does the initiation work for the tests. * @throws IOException//w w w.ja va 2s .co m * if an I/O error occurred * @throws NoSuchFieldException * if a field is not found */ @Before public void init() throws Exception { Map<String, PublicKey> appKey = new HashMap<String, PublicKey>(); X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY)); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey publicKey = kf.generatePublic(spec); SecurityEventUtil securityEventUtil = Mockito.mock(SecurityEventUtil.class); SecurityEvent event = createSE(); Mockito.when(securityEventUtil.createSecurityEvent(Mockito.anyString(), Mockito.anyString(), Mockito.eq(LogLevelType.TYPE_INFO), Mockito.anyString(), Mockito.any(BEMessageCode.class), Mockito.anyString())).thenReturn(event); Mockito.when(securityEventUtil.createSecurityEvent(Mockito.anyString(), Mockito.anyString(), Mockito.eq(LogLevelType.TYPE_ERROR), Mockito.any(BEMessageCode.class))).thenReturn(event); appKey.put(testApp, publicKey); archiveFile = new ExtractFile(new File("./"), FILE_NAME, clientKeys, securityEventUtil); archiveFile.setClientKeys(appKey); File parentDir = (File) PrivateAccessor.getField(archiveFile, "tempDir"); ManifestFile metaFile = new ManifestFile(parentDir); metaFile.generateMetaFile(new DateTime()); Assert.assertTrue(metaFile.getFile() != null); Assert.assertTrue(metaFile.getFile().getName() != null); PrivateAccessor.setField(archiveFile, "manifestFile", metaFile); Map<String, JsonFileWriter> files = new HashMap<String, JsonFileWriter>(); File studentFile = File.createTempFile("student", ".json.gz", parentDir); String fileNamePrefix = studentFile.getName().substring(0, studentFile.getName().indexOf(".json.gz")); JsonFileWriter studentExtractFile = new JsonFileWriter(parentDir, fileNamePrefix); PrivateAccessor.setField(studentExtractFile, "file", studentFile); files.put("student", studentExtractFile); PrivateAccessor.setField(archiveFile, "dataFiles", files); }
From source file:com.teasoft.teavote.util.Signature.java
private PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { Resource resource = res.getResource("classpath:gotaSafui"); byte[] pubKeyBytes; try (InputStream pubKeyInputStream = resource.getInputStream()) { pubKeyBytes = IOUtils.toByteArray(pubKeyInputStream); pubKeyBytes = Base64.decodeBase64(pubKeyBytes); }//w w w . j a v a 2 s . com X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN"); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); return pubKey; }
From source file:hudson.model.UsageStatistics.java
private Cipher getCipher() { try {/* www. java 2 s. com*/ if (key == null) { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); key = keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage))); } Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher; } catch (GeneralSecurityException e) { throw new Error(e); // impossible } }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
protected PublicKey readPublicKey(InputStream keyInput) throws IOException, GeneralSecurityException { InputStream input = new Base64InputStream(keyInput); byte[] encKey = IOUtil.toByteArray(input); IOUtil.close(input);/*from w w w. j a va 2s . co m*/ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); return pubKey; }
From source file:org.esupportail.papercut.services.PayBoxService.java
public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource( derPayboxPublicKeyFile);/*from w w w. j av a2s. c o m*/ InputStream fis = derPayboxPublicKeyRessource.getInputStream(); DataInputStream dis = new DataInputStream(fis); byte[] pubKeyBytes = new byte[fis.available()]; dis.readFully(pubKeyBytes); fis.close(); dis.close(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec); }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.security.JWTSecurityInterceptor.java
private boolean isValid(String jwtToken) { String[] jwtTokenValues = jwtToken.split("\\."); String jwtAssertion = null;/*from www .j a v a2 s.c o m*/ byte[] jwtSignature = null; if (jwtTokenValues.length > 0) { String value = new String(base64Url.decode(jwtTokenValues[0].getBytes())); JSONParser parser = new JSONParser(); try { jsonHeaderObject = (JSONObject) parser.parse(value); } catch (ParseException e) { log.error("Error occurred while parsing JSON header ", e); } } if (jwtTokenValues.length > 1) { jwtAssertion = jwtTokenValues[0] + "." + jwtTokenValues[1]; } if (jwtTokenValues.length > 2) { jwtSignature = base64Url.decode(jwtTokenValues[2].getBytes()); } if (jwtAssertion != null && jwtSignature != null) { try { File publicKeyFile = new File(System.getProperty(CommonConstants.CARBON_HOME), File.separator + PUBLIC_KEY_LOCATION); InputStream inStream = new FileInputStream(publicKeyFile); DataInputStream dis = new DataInputStream(inStream); byte[] keyBytes = new byte[(int) publicKeyFile.length()]; dis.readFully(keyBytes); dis.close(); String publicKeyPEM = new String(keyBytes); BASE64Decoder b64 = new BASE64Decoder(); byte[] decoded = b64.decodeBuffer(publicKeyPEM); X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey publicKey = kf.generatePublic(spec); Signature signature = Signature.getInstance(getSignatureAlgorithm(jsonHeaderObject)); signature.initVerify(publicKey); signature.update(jwtAssertion.getBytes()); return signature.verify(jwtSignature); } catch (Exception e) { log.error("Error occurred while validating signature", e); } } else { log.warn("No signature exist in the request."); return false; } return false; }
From source file:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton//w w w . j av a2 s .c o m SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) { File pemFile = new File(securityConfig.wildcardPemPath()); try { String content = IOUtils.toString(new FileReader(pemFile)); String contentPrivate = RSAUtils.extractPrivateKey(content); String contentPublic = RSAUtils.extractPublic(content); RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate)); X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic)); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; LOGGER.info( "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ", certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath()); return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates); } catch (IOException e) { throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e); } } else { try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray()); RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(), securityConfig.sslRootCaKsPassword().toCharArray()); if (key == null) { return null; } RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias()); List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream() .map(c -> (X509Certificate) c).collect(Collectors.toList()); LOGGER.info( "Using a CA SSL certificat {} from keystore to provide Certificat to all instances of Kodo Kojo. ", securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore")); return new SSLKeyPair(key, publicKey, x509Certificates.toArray(new X509Certificate[x509Certificates.size()])); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeySpecException | CertificateException | IOException e) { throw new RuntimeException("Unable to open default Keystore", e); } } }
From source file:org.xdi.oxauth.model.jws.RSASigner.java
@Override public boolean validateSignature(String signingInput, String signature) throws SignatureException { if (getSignatureAlgorithm() == null) { throw new SignatureException("The signature algorithm is null"); }/*from ww w.ja va 2 s .c o m*/ if (rsaPublicKey == null) { throw new SignatureException("The RSA public key is null"); } if (signingInput == null) { throw new SignatureException("The signing input is null"); } String algorithm = null; switch (getSignatureAlgorithm()) { case RS256: algorithm = "SHA-256"; break; case RS384: algorithm = "SHA-384"; break; case RS512: algorithm = "SHA-512"; break; default: throw new SignatureException("Unsupported signature algorithm"); } ASN1InputStream aIn = null; try { byte[] sigBytes = JwtUtil.base64urldecode(signature); byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING); RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec); Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] decSig = cipher.doFinal(sigBytes); aIn = new ASN1InputStream(decSig); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); MessageDigest hash = MessageDigest.getInstance(algorithm, "BC"); hash.update(sigInBytes); ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1); return MessageDigest.isEqual(hash.digest(), sigHash.getOctets()); } catch (IOException e) { throw new SignatureException(e); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (InvalidKeySpecException e) { throw new SignatureException(e); } catch (NoSuchPaddingException e) { throw new SignatureException(e); } catch (BadPaddingException e) { throw new SignatureException(e); } catch (NoSuchProviderException e) { throw new SignatureException(e); } catch (IllegalBlockSizeException e) { throw new SignatureException(e); } catch (Exception e) { throw new SignatureException(e); } finally { IOUtils.closeQuietly(aIn); } }
From source file:org.apache.usergrid.security.sso.ApigeeSSO2Provider.java
public PublicKey getPublicKey(String keyUrl) { if (keyUrl != null && !keyUrl.isEmpty()) { try {//from ww w . ja va 2 s .c o m Map<String, Object> publicKey = client.target(keyUrl).request().get(Map.class); String ssoPublicKey = publicKey.get(RESPONSE_PUBLICKEY_VALUE).toString().split("----\n")[1] .split("\n---")[0]; byte[] publicBytes = decodeBase64(ssoPublicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); return pubKey; } catch (Exception e) { throw new IllegalArgumentException("error getting public key"); } } return null; }
From source file:com.cellngine.crypto.RSACipher.java
private PublicKey getPublicKey(final RSAPublicKeySpec keySpec) { final KeyFactory factory = this.getKeyFactory(); try {//from w w w.jav a 2 s. com return factory.generatePublic(keySpec); } catch (final InvalidKeySpecException e) { LOG.error("Unable to get key spec from factory", e); return null; } }