List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec
public X509EncodedKeySpec(byte[] encodedKey)
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>/*from www . j a v a 2 s .c om*/ * * </p> * * @param encryptedData ? * @param publicKey (BASE64?) * @return byte * @throws Exception Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(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 index = 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); index++; offSet = index * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
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 w w w.jav a 2s .com 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:org.kde.kdeconnect.Device.java
Device(Context context, String deviceId) { settings = context.getSharedPreferences(deviceId, Context.MODE_PRIVATE); //Log.e("Device","Constructor A"); this.context = context; this.deviceId = deviceId; this.name = settings.getString("deviceName", context.getString(R.string.unknown_device)); this.pairStatus = PairStatus.Paired; this.protocolVersion = NetworkPackage.ProtocolVersion; //We don't know it yet this.deviceType = DeviceType.FromString(settings.getString("deviceType", "desktop")); try {//from w w w . ja v a 2s . c o m String publicKeyStr = settings.getString("publicKey", null); if (publicKeyStr != null) { byte[] publicKeyBytes = Base64.decode(publicKeyStr, 0); publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)); } } catch (Exception e) { e.printStackTrace(); Log.e("KDE/Device", "Exception deserializing stored public key for device"); } //Assume every plugin is supported until addLink is called and we can get the actual list m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins()); //Do not load plugins yet, the device is not present //reloadPluginsFromSettings(); }
From source file:org.jboss.aerogear.cordova.crypto.CryptoPlugin.java
private java.security.KeyPair parseKeyPairFromJson(byte[] encodedPublicKey, byte[] encodedPrivateKey) { try {/*ww w.j a va 2s . co m*/ KeyFactory fact = KeyFactory.getInstance("ECDH", AeroGearCrypto.PROVIDER); PublicKey publicKey2 = fact.generatePublic(new X509EncodedKeySpec(encodedPublicKey)); java.security.PrivateKey privateKey2 = fact.generatePrivate(new PKCS8EncodedKeySpec(encodedPrivateKey)); return new java.security.KeyPair(publicKey2, privateKey2); } catch (InvalidKeySpecException e) { throw new RuntimeException("could not reconstruct key pair from json!", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("could not reconstruct key pair from json!", e); } catch (NoSuchProviderException e) { throw new RuntimeException("could not reconstruct key pair from json!", e); } }
From source file:com.turo.pushy.apns.auth.ApnsVerificationKey.java
/** * Loads a verification key from the given input stream. * * @param inputStream the input stream from which to load the key * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs * @param keyId the ten-character, Apple-issued identitifier for the key itself * * @return an APNs verification key with the given key ID and associated with the given team * * @throws IOException if a key could not be loaded from the given file for any reason * @throws NoSuchAlgorithmException if the JVM does not support elliptic curve keys * @throws InvalidKeyException if the loaded key is invalid for any reason *//*ww w . ja va2s . co m*/ public static ApnsVerificationKey loadFromInputStream(final InputStream inputStream, final String teamId, final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException { final ECPublicKey verificationKey; { final String base64EncodedPublicKey; { final StringBuilder publicKeyBuilder = new StringBuilder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); boolean haveReadHeader = false; boolean haveReadFooter = false; for (String line; (line = reader.readLine()) != null;) { if (!haveReadHeader) { if (line.contains("BEGIN PUBLIC KEY")) { haveReadHeader = true; } } else { if (line.contains("END PUBLIC KEY")) { haveReadFooter = true; break; } else { publicKeyBuilder.append(line); } } } if (!(haveReadHeader && haveReadFooter)) { throw new IOException("Could not find public key header/footer"); } base64EncodedPublicKey = publicKeyBuilder.toString(); } final byte[] keyBytes = Base64.decodeBase64(base64EncodedPublicKey); final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); final KeyFactory keyFactory = KeyFactory.getInstance("EC"); try { verificationKey = (ECPublicKey) keyFactory.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } } return new ApnsVerificationKey(keyId, teamId, verificationKey); }
From source file:org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java
public String encryptMessage(String message, String key, String encoding) throws Exception { String urlDecodedKey;// w w w. j a v a 2 s. com byte[] encryptedMessage; urlDecodedKey = java.net.URLDecoder.decode(key, encoding); // Generate the public key from a String PublicKey pk = (PublicKey) KeyFactory.getInstance("RSA").generatePublic( new X509EncodedKeySpec(Base64.decodeBase64(urlDecodedKey.getBytes(defaultEncoding)))); // Get an instance of the Cipher for RSA encryption/decryption Cipher c = Cipher.getInstance("RSA"); // Initiate the Cipher, telling it that it is going to Encrypt, giving // it the public key c.init(Cipher.ENCRYPT_MODE, pk); // c.init(Cipher.ENCRYPT_MODE, extractInfo(key)); encryptedMessage = c.doFinal(message.getBytes(defaultEncoding)); return java.net.URLEncoder.encode(new String(Base64.encodeBase64(encryptedMessage)), encoding); }
From source file:com.cablevision.util.sso.UtilSSO.java
/** * Creates a PublicKey from the specified public key file and algorithm. * Returns null if failure to generate PublicKey. * // w w w . j a va 2 s . c o m * @param publicKeyFilepath location of public key file * @param algorithm algorithm of specified key file * @return PublicKey object representing contents of specified public key * file, null if error in generating key or invalid file specified */ public static PublicKey getPublicKey(String publicKeyFilepath, String algorithm) throws SamlException { try { InputStream pubKey = null; ClassLoader cl = Thread.currentThread().getContextClassLoader(); pubKey = cl.getResourceAsStream(publicKeyFilepath); byte[] bytes = IOUtils.toByteArray(pubKey); pubKey.close(); System.out.println("Private bytes: " + Arrays.toString(bytes)); pubKey.close(); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(algorithm); return factory.generatePublic(pubSpec); } catch (FileNotFoundException e) { throw new SamlException("ERROR: Public key file not found - " + publicKeyFilepath); } catch (IOException e) { throw new SamlException("ERROR: Invalid public key file - " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new SamlException("ERROR: Invalid public key algorithm - " + e.getMessage()); } catch (InvalidKeySpecException e) { throw new SamlException("ERROR: Invalid public key spec - " + e.getMessage()); } }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ???//w ww. j a v a2s . c o m * * @param data * ?? * @param publicKey * 2 * @param signature * base64???? * @return * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-12 ?5:37:18 */ public static boolean verifyBinKey(String data, byte[] publicKey, String signature) throws Exception { Base64 base64 = new Base64(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec); // ? Signature sign = Signature.getInstance("DSA"); sign.initVerify(pub); sign.update(data.getBytes("utf8")); // return sign.verify(decoder.decodeBuffer(signature)); return sign.verify(base64.decode(signature.getBytes("utf8"))); }
From source file:org.ow2.proactive.authentication.crypto.Credentials.java
/** * Retrieves a public key stored in a local file * <p>//from w w w. j a v a 2 s . co m * * @param pubPath path to the public key on the local filesystem * @return the key encapsulated in a regular JCE container * @throws KeyException the key could not be retrieved or is malformed */ public static PublicKey getPublicKey(String pubPath) throws KeyException { byte[] bytes; File f = new File(pubPath); FileInputStream fin; String algo = "", tmp = ""; // recover public key bytes try { fin = new FileInputStream(f); DataInputStream in = new DataInputStream(fin); int read, tot = 0; while ((read = in.read()) != '\n') { algo += (char) read; tot++; } tot++; while ((read = in.read()) != '\n') { tmp += (char) read; tot++; } tot++; bytes = new byte[(int) f.length() - tot]; in.readFully(bytes); in.close(); } catch (Exception e) { throw new KeyException("Could not retrieve public key from " + pubPath, e); } // reconstruct public key X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes); PublicKey pubKey; KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance(algo); } catch (NoSuchAlgorithmException e) { throw new KeyException("Cannot initialize key factory", e); } try { pubKey = keyFactory.generatePublic(pubKeySpec); } catch (InvalidKeySpecException e) { throw new KeyException("Cannot re-generate public key", e); } return pubKey; }
From source file:im.whistle.crypt.Crypt.java
/** * Decrypts a message./*from w w w . j av a2 s . c o m*/ * @param args Arguments: enc, privateKey, sig, publicKey * @param callback Callback */ public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { // Get the arguments String enc = args.getString(0); String key = args.getString(1); String sig = null; String pub = null; if (args.length() == 4) { sig = args.getString(2); pub = args.getString(3); } Boolean ver = null; // Convert everything into byte arrays byte[] encRaw = Base64.decode(enc, Base64.DEFAULT); byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT); // Verify signature if (sig != null && pub != null) { try { byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initVerify(kf.generatePublic(publicKeySpec)); s.update(encRaw); ver = s.verify(sigRaw); } catch (Exception ex) { Log.i("whistle", "Verification failed: " + ex.getMessage()); ver = false; } } // Split enc into encrypted aes data and remaining enc byte[] encSplit = encRaw; byte[] aesRaw = new byte[RSA_BYTES]; System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length); encRaw = new byte[encSplit.length - RSA_BYTES]; System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length); // Decrypt encrypted aes data using RSAES-OAEP PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding"); c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec)); aesRaw = c.doFinal(aesRaw); // Decrypted enc using AES-CBC byte[] aesKey = new byte[AES_BYTES]; byte[] aesIv = new byte[aesRaw.length - aesKey.length]; System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length); System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length); c = Cipher.getInstance("AES/CBC/PKCS7Padding"); c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); byte[] dec = c.doFinal(encRaw); JSONArray res = new JSONArray(); res.put(new String(dec, "utf-8")); res.put(ver); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex); callback.error(ex); } }