List of usage examples for java.security KeyFactory getInstance
public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.centurylink.mdw.services.util.AuthUtils.java
private static synchronized JWTVerifier createCustomTokenVerifier(String algorithmName, String issuer) { JWTVerifier tempVerifier = verifierCustom.get(issuer); if (tempVerifier == null) { Properties props = null;//ww w . j a v a 2 s . c om if (customProviders == null) { props = PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT); customProviders = new HashMap<>(); for (String pn : props.stringPropertyNames()) { String[] pnParsed = pn.split("\\.", 4); if (pnParsed.length == 4) { String issuer_name = pnParsed[2]; String attrname = pnParsed[3]; Properties issuerSpec = customProviders.get(issuer_name); if (issuerSpec == null) { issuerSpec = new Properties(); customProviders.put(issuer_name, issuerSpec); } String v = props.getProperty(pn); issuerSpec.put(attrname, v); } } } props = customProviders.get(getCustomProviderGroupName(issuer)); if (props == null) { logger.severe("Exception creating Custom JWT Verifier for " + issuer + " - Missing 'key' Property"); return null; } String propAlg = props.getProperty(PropertyNames.MDW_JWT_ALGORITHM); if (StringHelper.isEmpty(algorithmName) || (!StringHelper.isEmpty(propAlg) && !algorithmName.equals(propAlg))) { String message = "Exception creating Custom JWT Verifier - "; message = StringHelper.isEmpty(algorithmName) ? "Missing 'alg' claim in JWT" : ("Mismatch algorithm with specified Property for " + issuer); logger.severe(message); return null; } String key = System.getenv("MDW_JWT_" + getCustomProviderGroupName(issuer).toUpperCase() + "_KEY"); if (StringHelper.isEmpty(key)) { if (!algorithmName.startsWith("HS")) { // Only allow use of Key in MDW properties for asymmetric algorithms key = props.getProperty(PropertyNames.MDW_JWT_KEY); if (StringHelper.isEmpty(key)) { logger.severe("Exception creating Custom JWT Verifier for " + issuer + " - Missing 'key' Property"); return null; } } else { logger.severe("Could not find properties for JWT issuer " + issuer); return null; } } try { maxAge = PropertyManager.getIntegerProperty(PropertyNames.MDW_AUTH_TOKEN_MAX_AGE, 0) * 1000L; Algorithm algorithm = null; Method algMethod = null; if (algorithmName.startsWith("HS")) { // HMAC String methodName = "HMAC" + algorithmName.substring(2); algMethod = Algorithm.none().getClass().getMethod(methodName, String.class); algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), key); } else if (algorithmName.startsWith("RS")) { // RSA String methodName = "RSA" + algorithmName.substring(2); byte[] publicBytes = Base64.decodeBase64(key.getBytes()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); algMethod = Algorithm.none().getClass().getMethod(methodName, RSAPublicKey.class, RSAPrivateKey.class); algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), pubKey, null); } else { logger.severe( "Exception creating Custom JWT Verifier - Unsupported Algorithm: " + algorithmName); return null; } String subject = props.getProperty(PropertyNames.MDW_JWT_SUBJECT); Verification tmp = JWT.require(algorithm).withIssuer(issuer); tmp = StringHelper.isEmpty(subject) ? tmp : tmp.withSubject(subject); tempVerifier = tmp.build(); verifierCustom.put(issuer, tempVerifier); } catch (IllegalArgumentException | NoSuchAlgorithmException | NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException | InvalidKeySpecException e) { logger.severeException("Exception creating Custom JWT Verifier for " + issuer, e); } } return tempVerifier; }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, KeyStoreException {/*from w w w . j a v a 2 s. com*/ KeyInfoManager keyInfoManager = null; writeLock.lock(); try { keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation()); KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager); // loading Key byte[] keyBytes = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(keyBytes, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes); PrivateKey key = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); @SuppressWarnings("rawtypes") Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; certs = (Certificate[]) c.toArray(new Certificate[0]); // storing keystore ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs); if (logger.isDebugEnabled()) { logger.debug("Key and certificate stored."); logger.debug("Alias:" + keyAlias); } ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray()); } finally { if (keyInfoManager != null) { keyInfoManager.clear(); } writeLock.unlock(); } }
From source file:com.vmware.identity.idm.server.ServerUtils.java
public static PrivateKey getPrivateKeyValue(LdapValue[] value) { PrivateKey privateKey = null; if ((value != null) && (value.length == 1)) { byte[] privateKeyBytes = value[0].getValue(); if (privateKeyBytes != null) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); privateKey = keyFactory.generatePrivate(privateKeySpec); } catch (NoSuchAlgorithmException ex1) { throw new RuntimeException("No such algorithm"); } catch (InvalidKeySpecException ex2) { throw new RuntimeException("Invalid key spec"); }//from w w w.j a v a 2s . com } } return privateKey; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This assumes that authentication is the last piece of info in handshake */// www . j av a 2 s. c o m public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (p_credentials == null) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply byte acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } byte[] challenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { DataSerializer.writeProperties(p_credentials, hdos); // Also add the challenge string DataSerializer.writeByteArray(challenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); }
From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java
private PublicKey extractPublicKey(String source) { // Java wants the key formatted without prefix and postfix. String prefix = "-----BEGIN RSA PUBLIC KEY-----"; String postfix = "\n-----END RSA PUBLIC KEY-----"; // Java's string formatting/slicing is... 'slightly' inferior to python's. String keyNoPrefix = source.substring(prefix.length()); String reversed = new StringBuilder(keyNoPrefix).reverse().toString(); String reversedNoPostfix = reversed.substring(postfix.length()); String keyString = new StringBuilder(reversedNoPostfix).reverse().toString(); keyString = keyString.replace("\n", ""); ASN1InputStream in = new ASN1InputStream(Base64.decode(keyString, Base64.NO_WRAP)); ASN1Primitive obj;//from ww w.jav a 2 s .co m try { obj = in.readObject(); } catch (IOException e) { return null; } RSAPublicKey key = RSAPublicKey.getInstance(obj); RSAPublicKeySpec keySpec = null; if (key != null) { keySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); } KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { // Cannot happen. } PublicKey pubkey = null; try { if (keyFactory != null) { pubkey = keyFactory.generatePublic(keySpec); } } catch (InvalidKeySpecException e) { // Cannot (SHOULD NOT) happen. } return pubkey; }
From source file:cn.usually.common.pay.union.sdknew.SecureUtil.java
public static PublicKey getPublicKey(String modulus, String exponent) { try {//from w w w . j a v a2 s .c o m BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return keyFactory.generatePublic(keySpec); } catch (Exception e) { throw new RuntimeException("getPublicKey error", e); } }
From source file:com.netscape.cms.servlet.test.DRMTest.java
/** * Verify the generated asymmetric key pair. * * @param keyAlgorithm - Algorithm used to generate keys. * @param privateKey - binary data of the private key. * @param publicKey - binary data of he public key. * @return//from ww w . j av a 2s .c om * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws InvalidKeyException * @throws SignatureException * @throws IOException */ public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, IOException { String algorithm = keyAlgorithm.toUpperCase(); String signingAlgorithm = "SHA1with" + algorithm; KeyFactory factory = KeyFactory.getInstance(algorithm); PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey)); PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey)); Signature sig = Signature.getInstance(signingAlgorithm); sig.initSign(priKey); String s = "Data to test asymmetric keys."; sig.update(s.getBytes()); // Sign the data with the private key. byte[] realSig = sig.sign(); Signature sig2 = Signature.getInstance(signingAlgorithm); sig2.initVerify(pubKey); sig2.update(s.getBytes()); // Verify the signature with the public key. return sig2.verify(realSig); }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
private PublicKey getPublicKey(String strPublickey) { try {/*ww w. ja va 2 s . c om*/ KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] rawPublicKey = org.apache.commons.codec.binary.Base64.decodeBase64(strPublickey.getBytes()); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(rawPublicKey); return keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java
/** * RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) using SHA-256 * /* w ww . j av a 2 s. c o m*/ * @param modulus_n * @param exponent_e * @param signinInput_M * @param signature_S * @return * @throws SignatureException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ static boolean RSASSA_PKCS1_V1_5_VERIFY(String modulus_n, String exponent_e, String signinInput_M, String signature_S) throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { Debug.println("Starting verification"); /* RSA SHA-256 RSASSA-PKCS1-V1_5-VERIFY */ // Modulus (n from https://www.googleapis.com/oauth2/v2/certs) String n = modulus_n; // Exponent (e from https://www.googleapis.com/oauth2/v2/certs) String e = exponent_e; // The JWT Signing Input (JWT Header and JWT Payload concatenated with // ".") byte[] M = signinInput_M.getBytes(); // Signature (JWT Crypto) byte[] S = Base64.decodeBase64(signature_S); byte[] modulusBytes = Base64.decodeBase64(n); byte[] exponentBytes = Base64.decodeBase64(e); BigInteger modulusInteger = new BigInteger(1, modulusBytes); BigInteger exponentInteger = new BigInteger(1, exponentBytes); RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulusInteger, exponentInteger); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(rsaPubKey); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(pubKey); signature.update(M); boolean isVerified = signature.verify(S); Debug.println("Verify result [" + isVerified + "]"); return isVerified; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This method writes what readCredential() method expects to read. (Note the use of singular * credential). It is similar to writeCredentials(), except that it doesn't write * credential-properties.// ww w .j av a2s . c om */ public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); this.appSecureMode = CREDENTIALS_NORMAL; // DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } byte acceptanceCode = -1; try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); this.appSecureMode = CREDENTIALS_DHENCRYPT; heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } // Read server challenge bytes byte[] serverChallenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { // Add the challenge string DataSerializer.writeByteArray(serverChallenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); return acceptanceCode; }