/** * Created primary key using openssl. * * <p>openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj * '/C=GB/ST=/L=Manchester/CN=www.example.com' -keyout myrsakey.pem -out /tmp/myrsacert.pem * openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8 */ private static PrivateKey getPrivateKey() { String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww=="; try { KeyFactory fac = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str)); return fac.generatePrivate(privKeySpec); } catch (Exception e) { throw new RuntimeException(e); } }
public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] localObject = null; if (paramE_CODE == E_CODE.RSA) { if (rsa_key.length() > 2) { Cipher localCipher; byte[] arrayOfByte = new byte[0]; // PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new // X509EncodedKeySpec(Base64.decodeBase64(rsa_key))); PublicKey localPublicKey = KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT))); System.out.println("key length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length); System.out.println("data length-" + paramArrayOfByte.length); localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); localCipher.init(Cipher.DECRYPT_MODE, localPublicKey); // localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey); arrayOfByte = localCipher.doFinal(paramArrayOfByte); // int oldLength; // for (int i = 0; i < paramArrayOfByte.length; i += 8) { // byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8); // oldLength = arrayOfByte.length; // arrayOfByte = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length); // System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length); // } // arrayOfByte = paramArrayOfByte; return arrayOfByte; } } else if (paramE_CODE == E_CODE.RSA_EP) { if (rsa_ep_key.length() >= 2) { // PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key))); PrivateKey localPrivateKey = KeyFactory.getInstance("RSA") .generatePrivate( new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT))); Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); localCipher2.init(2, localPrivateKey); localObject = localCipher2.doFinal(paramArrayOfByte); } } else if (paramE_CODE == E_CODE.AES) { // SecretKeySpec localSecretKeySpec = new // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES"); // byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte); SecretKeySpec localSecretKeySpec = new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES"); byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT); Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding"); localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec); byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1); localObject = arrayOfByte2; } return localObject; }
/** * 私钥加密 * * @param data 源数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateK); 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; }
@Kroll.method public String encode(HashMap args) { // encode text to cipher text // KrollDict arg = new KrollDict(args); String txt = arg.getString("plainText"); String keyString = arg.getString("publicKey"); byte[] encodedBytes = null; Key key; try { byte[] encodedKey = Base64.decode(keyString, 0); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); key = keyFact.generatePublic(x509KeySpec); } catch (Exception e) { return "error key"; } try { Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.ENCRYPT_MODE, key); encodedBytes = c.doFinal(txt.getBytes()); } catch (Exception e) { Log.e(TAG, "RSA encryption error " + e.toString()); } return Base64.encodeToString(encodedBytes, Base64.NO_WRAP); }
/** * 生成公钥 * * @param modulus * @param publicExponent * @return RSAPublicKey * @throws Exception */ public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } }
private static PrivateKey derivePrivateKeyPBES2( org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, InvalidCipherTextException { PBES2Parameters pbeParams = new PBES2Parameters((ASN1Sequence) algId.getParameters()); CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams); EncryptionScheme scheme = pbeParams.getEncryptionScheme(); BufferedBlockCipher cipher; if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) { RC2CBCParameter rc2Params = new RC2CBCParameter((ASN1Sequence) scheme.getObject()); byte[] iv = rc2Params.getIV(); CipherParameters param = new ParametersWithIV(cipherParams, iv); cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine())); cipher.init(false, param); } else { byte[] iv = ((ASN1OctetString) scheme.getObject()).getOctets(); CipherParameters param = new ParametersWithIV(cipherParams, iv); cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine())); cipher.init(false, param); } byte[] data = eIn.getEncryptedData(); byte[] out = new byte[cipher.getOutputSize(data.length)]; int len = cipher.processBytes(data, 0, data.length, out, 0); len += cipher.doFinal(out, len); byte[] pkcs8 = new byte[len]; System.arraycopy(out, 0, pkcs8, 0, len); KeyFactory fact = KeyFactory.getInstance("RSA"); // It seems to work for both RSA and DSA. return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8)); }
public static PublicKeyRecord createNew(KeyPair kp) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); int id = 0; try { Connection conn = DatabaseConnection.getConn(); String sql = "insert into publickey modulus = ?, exponent = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, pub.getModulus().toString()); stmt.setString(2, pub.getPublicExponent().toString()); stmt.executeUpdate(); ResultSet generatedKeys = stmt.getGeneratedKeys(); if (generatedKeys.next()) { id = generatedKeys.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return get(id); }
/** * 生成RSA公钥 * * @param publicKeyStr * @return * @throws Exception */ public PublicKey generateRSAPublicKey(String publicKeyStr) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(publicKeyStr)); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); return publicKey; }
@Override protected Key initDecryptKey() throws Exception { KeyFactory mykeyFactory = KeyFactory.getInstance(getAlgorithm()); PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(getDecryptKey()); PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec); return privKey; }
@Override protected Key initEncryptKey() throws Exception { KeyFactory mykeyFactory = KeyFactory.getInstance(getAlgorithm()); X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(getEncryptKey()); PublicKey pubKey = mykeyFactory.generatePublic(pub_spec); return pubKey; }
private KeyPair loadKey(final JSONObject keys) { if (keys == null) { return null; } synchronized (keys) { try { BigInteger x = new BigInteger(keys.getString("otr_x"), 16); BigInteger y = new BigInteger(keys.getString("otr_y"), 16); BigInteger p = new BigInteger(keys.getString("otr_p"), 16); BigInteger q = new BigInteger(keys.getString("otr_q"), 16); BigInteger g = new BigInteger(keys.getString("otr_g"), 16); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, p, q, g); DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g); PublicKey publicKey = keyFactory.generatePublic(pubKeySpec); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return new KeyPair(publicKey, privateKey); } catch (JSONException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (InvalidKeySpecException e) { return null; } } }
private static void _initKeys() { ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader(); if ((classLoader == null) || (_encryptedSymmetricKey != null)) { return; } try { URL url = classLoader.getResource("com/liferay/portal/license/public.key"); byte[] bytes = IOUtils.toByteArray(url.openStream()); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128, new SecureRandom()); _symmetricKey = keyGenerator.generateKey(); byte[] encryptedSymmetricKey = Encryptor.encryptUnencoded(publicKey, _symmetricKey.getEncoded()); _encryptedSymmetricKey = Base64.objectToString(encryptedSymmetricKey); } catch (Exception e) { _log.error(e, e); } }
public static PrivateKey readPrivateKey(byte[] bytesPrivateKey) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException { KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytesPrivateKey); PrivateKey pk = kf.generatePrivate(spec); return pk; }
private PublicKey loadRemotePublicKeyFromStore(String fullUserId) { // if (!Address.hasResource(fullUserId)) // return null; byte[] b64PubKey = this.store.getPropertyBytes(fullUserId + ".publicKey"); if (b64PubKey == null) { return null; } X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey); // Generate KeyPair from spec KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance(KEY_ALG); return keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; } }
private KeyPair loadLocalKeyPair(String fullUserId) { PublicKey publicKey; PrivateKey privateKey; String userId = Address.stripResource(fullUserId); try { // Load Private Key. byte[] b64PrivKey = this.store.getPropertyBytes(userId + ".privateKey"); if (b64PrivKey == null) return null; PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey); // Generate KeyPair. KeyFactory keyFactory; keyFactory = KeyFactory.getInstance(KEY_ALG); privateKey = keyFactory.generatePrivate(privateKeySpec); // Load Public Key. byte[] b64PubKey = this.store.getPropertyBytes(userId + ".publicKey"); if (b64PubKey == null) return null; X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; } return new KeyPair(publicKey, privateKey); }
public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { KeyPairGenerator kpg = null; kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256 kpg.initialize(gps); KeyPair apair = kpg.generateKeyPair(); ECPublicKey apub = (ECPublicKey) apair.getPublic(); ECParameterSpec aspec = apub.getParams(); byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false); byte[] publicKeybx = new byte[32]; byte[] publicKeyby = new byte[32]; System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32); System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32); BigInteger x = new BigInteger(1, publicKeybx); BigInteger y = new BigInteger(1, publicKeyby); java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y); ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec); ECPublicKey cpub = null; KeyFactory kfa = null; kfa = KeyFactory.getInstance("EC"); return cpub = (ECPublicKey) kfa.generatePublic(cpubs); }
public PublicKey retrieveJwkKey(String jwkUrl) { RSAPublicKey pub = null; try { String jwkString = restTemplate.getForObject(jwkUrl, String.class); JsonObject json = (JsonObject) new JsonParser().parse(jwkString); JsonArray getArray = json.getAsJsonArray("keys"); for (int i = 0; i < getArray.size(); i++) { JsonObject object = getArray.get(i).getAsJsonObject(); String algorithm = object.get("alg").getAsString(); if (algorithm.equals("RSA")) { byte[] modulusByte = Base64.decodeBase64(object.get("mod").getAsString()); BigInteger modulus = new BigInteger(1, modulusByte); byte[] exponentByte = Base64.decodeBase64(object.get("exp").getAsString()); BigInteger exponent = new BigInteger(1, exponentByte); RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); KeyFactory factory = KeyFactory.getInstance("RSA"); pub = (RSAPublicKey) factory.generatePublic(spec); } } } catch (HttpClientErrorException e) { logger.error("HttpClientErrorException in KeyFetcher.java: ", e); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException in KeyFetcher.java: ", e); } catch (InvalidKeySpecException e) { logger.error("InvalidKeySpecException in KeyFetcher.java: ", e); } return pub; }
/** * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(RSA); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; }
/** * 生成RSA私钥 * * @param privateKeyStr * @return * @throws Exception */ public PrivateKey generateRSAPrivateKey(String privateKeyStr) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr)); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec); return privateKey; }
/** * 通过私钥byte[]将公钥还原,适用于RSA算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(RSA); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; }
protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) throws InvalidKeyException { byte[] encoded = null; try { encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length); } catch (BadPaddingException e) { throw new InvalidKeyException(e.getMessage()); } catch (IllegalBlockSizeException e2) { throw new InvalidKeyException(e2.getMessage()); } if (wrappedKeyType == Cipher.SECRET_KEY) { return new SecretKeySpec(encoded, wrappedKeyAlgorithm); } else { try { KeyFactory kf = KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME); if (wrappedKeyType == Cipher.PUBLIC_KEY) { return kf.generatePublic(new X509EncodedKeySpec(encoded)); } else if (wrappedKeyType == Cipher.PRIVATE_KEY) { return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded)); } } catch (NoSuchProviderException e) { throw new InvalidKeyException("Unknown key type " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Unknown key type " + e.getMessage()); } catch (InvalidKeySpecException e2) { throw new InvalidKeyException("Unknown key type " + e2.getMessage()); } throw new InvalidKeyException("Unknown key type " + wrappedKeyType); } }
/** * Generates Private Key from BASE64 encoded string * * @param key BASE64 encoded string which represents the key * @return The PrivateKey * @throws java.lang.Exception */ public static PrivateKey getPrivateKeyFromString(String key) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); BASE64Decoder b64 = new BASE64Decoder(); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64.decodeBuffer(key)); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; }
private static Cipher createCipher(int mode, boolean isPrivate, byte[] key) throws InvalidKeyException, InvalidAlgorithmParameterException { try { KeyFactory factory = KeyFactory.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER_ALGORITHM); Key keyspec; if (isPrivate) { keyspec = factory.generatePrivate(new PKCS8EncodedKeySpec(key)); } else { keyspec = factory.generatePublic(new X509EncodedKeySpec(key)); } Cipher cipher = Cipher.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER); cipher.init(mode, keyspec); return cipher; } catch (InvalidKeySpecException e) { throw new IllegalConfigurationException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalConfigurationException(e); } catch (NoSuchPaddingException e) { throw new IllegalConfigurationException(e); } }
/** * Generates Public Key from BASE64 encoded string * * @param key BASE64 encoded string which represents the key * @return The PublicKey * @throws java.lang.Exception */ public static PublicKey getPublicKeyFromString(String key) throws Exception { BASE64Decoder b64 = new BASE64Decoder(); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64.decodeBuffer(key)); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); return publicKey; }
public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception { PrivateKey privateKey = null; Certificate[] certs = null; while (uploadedFilesIterator.hasNext()) { FileItem fileItem = uploadedFilesIterator.next(); if (!fileItem.isFormField()) { if ("keyFile".equals(fileItem.getFieldName())) { KeyFactory kf = KeyFactory.getInstance("RSA"); privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get())); } if ("certFile".equals(fileItem.getFieldName())) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {}); } } } if (privateKey == null || certs == null) { throw new WebApplicationException( Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build()); } keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs); save(); }
public static KeyPair LoadKeyPair(String path, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Public Key. File filePublicKey = new File(path + "/public.key"); FileInputStream fis = new FileInputStream(path + "/public.key"); byte[] encodedPublicKey = new byte[(int) filePublicKey.length()]; fis.read(encodedPublicKey); fis.close(); // Read Private Key. File filePrivateKey = new File(path + "/private.key"); fis = new FileInputStream(path + "/private.key"); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); fis.close(); // Generate KeyPair. 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); }
@Kroll.method public String decode(HashMap args) { // decode string back to plain text // KrollDict arg = new KrollDict(args); String txt = arg.getString("cipherText"); byte[] bytesEncoded = Base64.decode(txt, 0); String keyString = arg.getString("privateKey"); PrivateKey key; try { byte[] encodedKey = Base64.decode(keyString, 0); PKCS8EncodedKeySpec x509KeySpec = new PKCS8EncodedKeySpec(encodedKey); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); key = keyFact.generatePrivate(x509KeySpec); } catch (Exception e) { return "error key"; } byte[] decodedBytes = null; try { Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.DECRYPT_MODE, key); decodedBytes = c.doFinal(bytesEncoded); } catch (Exception e) { Log.e(TAG, "RSA decryption error " + e.toString()); return "error"; } return new String(decodedBytes); }
public SymmetricCryptor getSymmetricCryptor( byte[] peerPublicKeyBytes, boolean useSealedObject, ClassLoader classLoader) throws CryptoException { if (privateKey == null) { throw new IllegalStateException( "KeyGenerator did not successfully generate public key"); //$NON-NLS-1$ } try { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(peerPublicKeyBytes); KeyFactory keyFact = KeyFactory.getInstance(ALGORITHM); PublicKey publicKey = keyFact.generatePublic(x509KeySpec); KeyAgreement ka = KeyAgreement.getInstance(ALGORITHM); ka.init(privateKey); ka.doPhase(publicKey, true); byte[] secret = ka.generateSecret(); MessageDigest sha = MessageDigest.getInstance(DIGEST); byte[] hash = sha.digest(secret); byte[] symKey = new byte[keySize / 8]; System.arraycopy(hash, 0, symKey, 0, symKey.length); SymmetricCryptor sc = SymmetricCryptor.getSymmectricCryptor(symKey); sc.setUseSealedObject(useSealedObject); sc.setClassLoader(classLoader); return sc; } catch (NoSuchAlgorithmException e) { throw new CryptoException(CorePlugin.Event.TEIID10003, e); } catch (InvalidKeySpecException e) { throw new CryptoException(CorePlugin.Event.TEIID10004, e); } catch (InvalidKeyException e) { throw new CryptoException(CorePlugin.Event.TEIID10005, e); } }
public PublicKey getPublicCAKey() throws InvalidKeySpecException, IOException, NoSuchAlgorithmException, NoSuchProviderException { ChipAuthenticationPublicKeyInfo info = securityInfos.getDefaultChipAuthenticationPublicKeyInfo(); AlgorithmParameterSpec algorithmParameterSpec = securityInfos.getDefaultCADomainParameter().getAlgorithmParameterSpec(); Type type = securityInfos.getDefaultCADomainParameter().getType(); PublicKey pubKey = null; if (type == Type.ECDH) { ECParameterSpec eps = (ECParameterSpec) algorithmParameterSpec; DEROctetString dos = new DEROctetString(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes()); ECPoint point = new X9ECPoint(eps.getCurve(), dos).getPoint(); ECPublicKeySpec eks = new ECPublicKeySpec(point, eps); pubKey = new JCEECPublicKey(type.toString(), eks); } else { DHParameterSpec dps = (DHParameterSpec) algorithmParameterSpec; ASN1Integer dos = new ASN1Integer(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes()); DHPublicKeySpec keySpec = new DHPublicKeySpec(dos.getPositiveValue(), dps.getP(), dps.getG()); KeyFactory kf = KeyFactory.getInstance(type.toString()); return kf.generatePublic(keySpec); } return pubKey; }
/** * Returns the key pair (private and public key) for the local machine * * @param sessionID sessionID for currect machine */ public KeyPair loadLocalKeyPair(SessionID sessionID) { if (sessionID == null) return null; String accountID = sessionID.getAccountID(); // Load Private Key. byte[] b64PrivKey = this.store.getPropertyBytes(accountID + ".privateKey"); if (b64PrivKey == null) return null; PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey); // Load Public Key. byte[] b64PubKey = this.store.getPropertyBytes(accountID + ".publicKey"); if (b64PubKey == null) return null; X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey); PublicKey publicKey; PrivateKey privateKey; // Generate KeyPair. KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance("DSA"); publicKey = keyFactory.generatePublic(publicKeySpec); privateKey = keyFactory.generatePrivate(privateKeySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; } return new KeyPair(publicKey, privateKey); }