/**
   * 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);
    }
  }
  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);
  }
Exemplo n.º 3
0
  @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);
  }
Exemplo n.º 4
0
  /**
   * 生成公钥
   *
   * @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());
    }
  }
Exemplo n.º 5
0
  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));
  }
Exemplo n.º 6
0
 /**
  * 生成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;
 }
  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);
  }
Exemplo n.º 8
0
 @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;
 }
Exemplo n.º 9
0
 public PublicKey getRawPublicKey() throws SshException {
   try {
     PublicKey key;
     String keyAlg = getString();
     if (KeyPairProvider.SSH_RSA.equals(keyAlg)) {
       BigInteger e = getMPInt();
       BigInteger n = getMPInt();
       KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA");
       key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e));
     } else if (KeyPairProvider.SSH_DSS.equals(keyAlg)) {
       BigInteger p = getMPInt();
       BigInteger q = getMPInt();
       BigInteger g = getMPInt();
       BigInteger y = getMPInt();
       KeyFactory keyFactory = SecurityUtils.getKeyFactory("DSA");
       key = keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g));
     } else {
       throw new IllegalStateException("Unsupported algorithm: " + keyAlg);
     }
     return key;
   } catch (InvalidKeySpecException e) {
     throw new SshException(e);
   } catch (NoSuchAlgorithmException e) {
     throw new SshException(e);
   } catch (NoSuchProviderException e) {
     throw new SshException(e);
   }
 }
Exemplo n.º 10
0
 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;
     }
   }
 }
Exemplo n.º 11
0
 @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;
 }
Exemplo n.º 12
0
  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);
    }
  }
Exemplo n.º 13
0
 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;
    }
  }
Exemplo n.º 15
0
  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);
  }
Exemplo n.º 16
0
 /**
  * 通过公钥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;
 }
  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;
  }
Exemplo n.º 18
0
 /**
  * 通过私钥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;
 }
Exemplo n.º 19
0
 /**
  * 生成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;
 }
Exemplo n.º 20
0
 /**
  * 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;
 }
Exemplo n.º 21
0
  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);
    }
  }
Exemplo n.º 22
0
 /**
  * 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;
 }
    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);
      }
    }
Exemplo n.º 24
0
  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);
  }
  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();
  }
Exemplo n.º 26
0
  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);
    }
  }
Exemplo n.º 27
0
  @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);
  }
Exemplo n.º 28
0
  /**
   * 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);
  }
Exemplo n.º 29
0
  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;
  }
Exemplo n.º 30
0
 /**
  * 私钥加密
  *
  * @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;
 }