List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java
/** * ?public key//w w w . j ava 2s .co m * * @throws RuntimeException key */ public static PublicKey readPublicKey(byte[] keyBytes) throws RuntimeException { try { KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); byte[] encodedKey = Base64.decodeBase64(keyBytes); EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); return keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }
From source file:com.intuit.s3encrypt.S3Encrypt.java
public static KeyPair loadKeyPair(String filename, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read public key from file. FileInputStream keyfis = new FileInputStream(filename + ".pub"); byte[] encodedPublicKey = new byte[keyfis.available()]; keyfis.read(encodedPublicKey);//from w w w . j av a2 s . c om keyfis.close(); // Read private key from file. keyfis = new FileInputStream(filename); byte[] encodedPrivateKey = new byte[keyfis.available()]; keyfis.read(encodedPrivateKey); keyfis.close(); // Generate KeyPair from public and private keys. KeyFactory keyFactory = KeyFactory.getInstance(algorithm); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return new KeyPair(publicKey, privateKey); }
From source file:de.ub0r.android.lib.DonationHelper.java
/** * Check for signature updates.//from ww w .j a va2s. com * * @param context * {@link Context} * @param s * signature * @param h * hash * @return true if ads should be hidden */ public static boolean checkSig(final Context context, final String s, final String h) { Log.d(TAG, "checkSig(ctx, " + s + ", " + h + ")"); boolean ret = false; try { final byte[] publicKey = Base64Coder.decode(KEY); final KeyFactory keyFactory = KeyFactory.getInstance(ALGO); PublicKey pk = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey)); Log.d(TAG, "hash: " + h); final String cs = s.replaceAll(" |\n|\t", ""); Log.d(TAG, "read sig: " + cs); try { byte[] signature = Base64Coder.decode(cs); Signature sig = Signature.getInstance(SIGALGO); sig.initVerify(pk); sig.update(h.getBytes()); ret = sig.verify(signature); Log.d(TAG, "ret: " + ret); } catch (IllegalArgumentException e) { Log.w(TAG, "error reading signature", e); } } catch (Exception e) { Log.e(TAG, "error reading signatures", e); } if (!ret) { Log.i(TAG, "sig: " + s); } return ret; }
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;//www.j av a 2 s. com 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:gemlite.core.util.RSAUtils.java
/** * <p>//from w w w . j a v a 2 s .c om * ?? * </p> * * @param data * ? * @param publicKey * (BASE64?) * @param sign * ?? * * @return * @throws Exception * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data); return signature.verify(Base64Utils.decode(sign)); }
From source file:gemlite.core.util.RSAUtils.java
/** * <p>//from w w w . j a v a 2 s . c o m * * </p> * * @param encryptedData * ? * @param publicKey * (BASE64?) * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
From source file:gemlite.core.util.RSAUtils.java
/** * <p>/* w w w . jav a 2 s.co m*/ * * </p> * * @param data * ?? * @param publicKey * (BASE64?) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // ? Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java
/** * Decode based on X, Y 32 byte integers * @param pubKey// w ww . j a va 2 s. c o m * @param curveName - Example secp256r1 * @return * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException { ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName); KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); ECNamedCurveSpec params = new ECNamedCurveSpec(curveName, spec.getCurve(), spec.getG(), spec.getN()); ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params); ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec); return pk; }
From source file:strat.mining.stratum.proxy.Launcher.java
/** * Check that a valid SSl certificate already exists. If not, create a new * one./*from w w w.j ava 2s.c o m*/ * * @throws Exception */ private static void checkCertificate() throws Exception { File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME); KeyStore keyStore = KeyStore.getInstance("JKS"); if (!storeFile.exists()) { LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath()); storeFile.getParentFile().mkdirs(); storeFile.createNewFile(); keyStore.load(null, null); LOGGER.info("Generating new SSL certificate."); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator(); keyGenerator .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14)); AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair(); RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate(); RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getExponent()); RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic(); RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec); PublicKey rsaPub = kf.generatePublic(rsaPublicSpec); X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); Integer randomNumber = new SecureRandom().nextInt(); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); byte[] publickeyb = rsaPub.getEncoded(); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb); SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subPubKeyInfo); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keysPair.getPrivate()); X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner); Certificate certificate = new CertificateFactory() .engineGenerateCertificate(new ByteBufferBackedInputStream( ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()))); LOGGER.info("Certificate generated."); keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray()); } }
From source file:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java
/** * Generates Public Key from BASE64 encoded string * @param key BASE64 encoded string which represents the key * @return The PublicKey/*from w w w .j av a2s. co m*/ * @throws java.lang.Exception */ public static PublicKey getPublicKeyFromString(String key) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodeBASE64(key)); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); return publicKey; }