public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (RandomValueMeta) smi;
    data = (RandomValueData) sdi;

    if (super.init(smi, sdi)) {
      data.readsRows = getStepMeta().getRemoteInputSteps().size() > 0;
      List<StepMeta> previous = getTransMeta().findPreviousSteps(getStepMeta());
      if (previous != null && previous.size() > 0) {
        data.readsRows = true;
      }
      boolean genHmacMD5 = false;
      boolean genHmacSHA1 = false;
      boolean uuid4 = false;

      for (int i = 0; i < meta.getFieldName().length; i++) {
        switch (meta.getFieldType()[i]) {
          case RandomValueMeta.TYPE_RANDOM_MAC_HMACMD5:
            genHmacMD5 = true;
            break;
          case RandomValueMeta.TYPE_RANDOM_MAC_HMACSHA1:
            genHmacSHA1 = true;
            break;
          case RandomValueMeta.TYPE_RANDOM_UUID4:
            uuid4 = true;
            break;
          default:
            break;
        }
      }
      if (genHmacMD5) {
        try {
          data.keyGenHmacMD5 = KeyGenerator.getInstance("HmacMD5");
        } catch (NoSuchAlgorithmException s) {
          logError(
              BaseMessages.getString(
                  PKG, "RandomValue.Log.HmacMD5AlgorithmException", s.getMessage()));
          return false;
        }
      }
      if (genHmacSHA1) {
        try {
          data.keyGenHmacSHA1 = KeyGenerator.getInstance("HmacSHA1");
        } catch (NoSuchAlgorithmException s) {
          logError(
              BaseMessages.getString(
                  PKG, "RandomValue.Log.HmacSHA1AlgorithmException", s.getMessage()));
          return false;
        }
      }
      if (uuid4) {
        data.u4 = new UUID4Util();
      }
      return true;
    }
    return false;
  }
 public static Mi ck(Context context) {
   Mi mi = new Mi();
   String key1 = "";
   try {
     key1 = org.dayup.decription.Utils.getDigest();
   } catch (NoSuchAlgorithmException e) {
     Log.e(TAG, e.getMessage());
   }
   Cursor cursor = null;
   try {
     cursor =
         context
             .getContentResolver()
             .query(Uri.parse(CONTENT_KEY), null, null, new String[] {key1}, null);
     if (cursor != null && cursor.moveToFirst()) {
       int cols = cursor.getColumnCount();
       if (cols == 1) { // key.version = 1
         mi.setV(1);
         mi.setLc(System.currentTimeMillis());
         mi.setIrk(key1.equals(cursor.getString(0)));
       } else {
         mi.setLc(cursor.getLong(3));
         mi.setV(cursor.getInt(2));
         mi.setK2(cursor.getString(1));
         mi.setK1(cursor.getString(0));
         try {
           mi.setIrk(
               key1.equals(mi.getK1())
                   && org.dayup.decription.Utils.getDigest2("" + mi.getLc()).equals(mi.getK2())
                   && mi.getLc() % 2 == 0);
         } catch (NoSuchAlgorithmException e) {
           mi.setIrk(false);
           Log.e(TAG, e.getMessage());
         }
       }
     } else {
       return null;
     }
   } catch (SecurityException se) {
     mi.setIrk(false);
     Toast.makeText(
             context,
             "Invalid app apk, please install/update it from Android Market.",
             Toast.LENGTH_LONG)
         .show();
     Log.e(TAG, se.getMessage());
   } finally {
     if (cursor != null) {
       cursor.close();
     }
   }
   return mi;
 }
Beispiel #3
0
  /**
   * mdsum the byte array with a limit
   *
   * @param input to sum
   * @param limit to stop at
   * @return String md5sum
   */
  public static String md5Sum(byte[] input, int limit) {
    try {
      if (md == null) {
        md = MessageDigest.getInstance("MD5");
      }

      md.reset();
      byte[] digest;

      if (limit == -1) {
        digest = md.digest(input);
      } else {
        md.update(input, 0, limit > input.length ? input.length : limit);
        digest = md.digest();
      }

      StringBuilder hexString = new StringBuilder();

      for (int i = 0; i < digest.length; i++) {
        hexString.append(hexDigit(digest[i]));
      }

      return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e.getMessage());
    }
  }
 /**
  * Get a digest for a generic algorithm, and rethrow an unchecked exception on failure
  *
  * @param algorithm the algorithm to use, e.g. MD5
  * @return a message digest for the given algorithm
  */
 protected static MessageDigest getDigest(String algorithm) {
   try {
     return MessageDigest.getInstance(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e.getMessage());
   }
 }
  /**
   * ִ��http���á�true:�ɹ� false:ʧ��
   *
   * @return boolean
   */
  public boolean call() {

    boolean isRet = false;

    // http
    if (null == this.caFile && null == this.certFile) {
      try {
        this.callHttp();
        isRet = true;
      } catch (IOException e) {
        this.errInfo = e.getMessage();
      }
      return isRet;
    }

    // https
    try {
      this.callHttps();
      isRet = true;
    } catch (UnrecoverableKeyException e) {
      this.errInfo = e.getMessage();
    } catch (KeyManagementException e) {
      this.errInfo = e.getMessage();
    } catch (CertificateException e) {
      this.errInfo = e.getMessage();
    } catch (KeyStoreException e) {
      this.errInfo = e.getMessage();
    } catch (NoSuchAlgorithmException e) {
      this.errInfo = e.getMessage();
    } catch (IOException e) {
      this.errInfo = e.getMessage();
    }

    return isRet;
  }
  /** Return the digest associated with given principal's user name. */
  protected String getDigest(String username, String realmName) {
    if (md5Helper == null) {
      try {
        md5Helper = MessageDigest.getInstance("MD5");
      } catch (NoSuchAlgorithmException e) {
        log.error("Couldn't get MD5 digest: ", e);
        throw new IllegalStateException(e.getMessage());
      }
    }

    if (hasMessageDigest()) {
      // Use pre-generated digest
      return getPassword(username);
    }

    String digestValue = username + ":" + realmName + ":" + getPassword(username);

    byte[] valueBytes = null;
    try {
      valueBytes = digestValue.getBytes(getDigestCharset());
    } catch (UnsupportedEncodingException uee) {
      log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
      throw new IllegalArgumentException(uee.getMessage());
    }

    byte[] digest = null;
    // Bugzilla 32137
    synchronized (md5Helper) {
      digest = md5Helper.digest(valueBytes);
    }

    return md5Encoder.encode(digest);
  }
Beispiel #7
0
  private void cambiarBtnActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_cambiarBtnActionPerformed
    char[] claveActualChar = claveActualTF.getPassword();
    char[] claveNuevaChar = claveNuevaTF.getPassword();

    String claveActual = new String(claveActualChar);
    String claveNueva = new String(claveNuevaChar);

    try {
      jp.cambiarClave("Administrador", claveActual, claveNueva);
      JOptionPane.showMessageDialog(
          rootPane, "Contraseña cambiada exitosamente.", "Mensaje", JOptionPane.OK_OPTION);
      this.setVisible(false);
    } catch (NoSuchAlgorithmException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (NoSuchPaddingException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (ClassNotFoundException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (InvalidKeyException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IllegalBlockSizeException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (BadPaddingException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (ClaveNoValidaException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IllegalArgumentException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    }
  } // GEN-LAST:event_cambiarBtnActionPerformed
  public static String calculateRFC2104HMACWithEncoding(String data, String key, boolean urlSafe)
      throws java.security.SignatureException {
    if (data == null) {
      throw new IllegalArgumentException("String data == null");
    }
    if (key == null) {
      throw new IllegalArgumentException("String key == null");
    }
    try {
      // Get an hmac_sha1 key from the raw key bytes
      byte[] keyBytes = key.getBytes("UTF-8");
      SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1_ALGORITHM);

      // Get an hmac_sha1 Mac instance and initialize with the signing key
      Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
      mac.init(signingKey);

      // Compute the hmac on input data bytes
      byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));

      // Convert raw bytes to encoding
      byte[] base64Bytes = Base64.encodeBase64(rawHmac, false, urlSafe);
      String result = new String(base64Bytes, "UTF-8");

      return result;

    } catch (NoSuchAlgorithmException e) {
      throw new SignatureException("Failed to generate HMAC : " + e.getMessage(), e);
    } catch (InvalidKeyException e) {
      throw new SignatureException("Failed to generate HMAC : " + e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
      throw new SignatureException("Failed to generate HMAC : " + e.getMessage(), e);
    }
  }
Beispiel #9
0
 /**
  * Kopiert Streams und erstellt MD5-Checksumme. Streams werden nicht geschlossen, aber output wird
  * geflusht.
  */
 public static byte[] copyStreamsWithChecksum(InputStream is, OutputStream os, String algo)
     throws IOException {
   MessageDigest md = null;
   if (algo != null) {
     try {
       md = MessageDigest.getInstance(algo);
     } catch (NoSuchAlgorithmException e) {
       log.log(e.getMessage(), Log.WARNINGS);
     }
   }
   BufferedOutputStream bos = null;
   BufferedInputStream bis = null;
   bos = new BufferedOutputStream(os);
   bis = new BufferedInputStream(is);
   byte[] buffer = new byte[65535];
   while (true) {
     int r = bis.read(buffer);
     if (r == -1) {
       break;
     }
     if (md != null) {
       md.update(buffer, 0, r);
     }
     bos.write(buffer, 0, r);
   }
   // bis.close(); Closing woild kill an outer zipinput or
   // objectinputstream
   bos.flush();
   // bos.close closing would kill an outer zipoutput or objectoutputstream
   if (md == null) {
     return null;
   }
   return md.digest();
 }
  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);
    }
  }
Beispiel #11
0
  static synchronized Random getRandom(String algorithm, Double seed) throws ExpressionException {

    algorithm = algorithm.toLowerCase();

    Random result = randoms.get(algorithm);

    if (result == null || !seed.isNaN()) {
      if (CFMXCompat.ALGORITHM_NAME.equalsIgnoreCase(algorithm)) {

        result = new Random();
      } else {

        try {

          result = SecureRandom.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
          throw new ExpressionException(
              "random algorithm [" + algorithm + "] is not installed on the system",
              e.getMessage());
        }
      }

      if (!seed.isNaN()) result.setSeed(seed.longValue());

      randoms.put(algorithm, result);
    }

    return result;
  }
Beispiel #12
0
  public static KeyPair getPrivateKey(String alias, char[] password)
      throws FileNotFoundException, IOException, CertificateException {
    try {

      KeyStore ks = KeyStore.getInstance("JKS");

      char[] passPhrase = "123456".toCharArray();
      // BASE64Encoder myB64 = new BASE64Encoder();

      File certificateFile = new File("C:\\Temp\\repositorio.jks");
      ks.load(new FileInputStream(certificateFile), passPhrase);

      // Get private key
      Key key = ks.getKey(alias, password);
      if (key instanceof PrivateKey) {
        // Get certificate of public key
        Certificate cert = ks.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        return new KeyPair(publicKey, (PrivateKey) key);
      }
    } catch (UnrecoverableKeyException e) {
      System.out.print(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      System.out.print(e.getMessage());
    } catch (KeyStoreException e) {
      System.out.print(e.getMessage());
    }
    return null;
  }
  /**
   * 对字符串进行 MD5 加密
   *
   * @param str 待加密字符串
   * @return 加密后字符串
   */
  public static String md5(String str) {
    char hexDigits[] = {
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
      md5.update(str.getBytes(UTF8));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
    byte[] encodedValue = md5.digest();
    int j = encodedValue.length;
    char finalValue[] = new char[j * 2];
    int k = 0;
    for (int i = 0; i < j; i++) {
      byte encoded = encodedValue[i];
      finalValue[k++] = hexDigits[encoded >> 4 & 0xf];
      finalValue[k++] = hexDigits[encoded & 0xf];
    }

    return new String(finalValue);
  }
  private boolean basicAuth(HttpServerRequest request, String encodedAuth) {
    byte[] authBytes = Base64.decodeBase64(encodedAuth);
    String decodedString = new String(authBytes);
    String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); // $NON-NLS-1$

    if (splitAuth.length != 2) return false;

    if (fileBasicAuthData.containsKey(splitAuth[0])) {
      String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0])));

      MessageDigest digest;
      try {
        digest = MessageDigest.getInstance("SHA-256"); // $NON-NLS-1$
        digest.update(splitAuth[1].getBytes());

        String receivedHash = new String(digest.digest());

        if (storedHash.equals(receivedHash)) {
          return true;
        }
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e.getCause());
      }
    }

    request
        .response()
        .headers()
        .add(
            "WWW-Authenticate",
            "Basic realm=\"" + config.getRealm() + "\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    return false;
  }
  public Key getDesEncryptionKey() throws PropertyManagerException {
    try {
      // get the key string
      String keyStr = getPropertyObject(DES_ENCRYPTION_KEY).getValue();

      // create a DES key spec
      DESKeySpec ks = new DESKeySpec(new sun.misc.BASE64Decoder().decodeBuffer(keyStr));

      // generate the key from the DES key spec
      return SecretKeyFactory.getInstance(DESPasswordEncoder.PASSWORD_ENCRYPTION_ALGORITHM)
          .generateSecret(ks);

    } catch (NoSuchAlgorithmException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (IOException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (ObjectNotFoundException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (InvalidKeyException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (InvalidKeySpecException e) {
      throw new PropertyManagerException(e.getMessage(), e);
    }
  }
 protected MessageDigest initialValue() {
   try {
     return MessageDigest.getInstance("MD5");
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalStateException(e.getMessage(), e);
   }
 }
Beispiel #17
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());
    }
  }
    @Override
    public InputStream sendXmlRpc(byte[] request) throws IOException {
      // Create a trust manager that does not validate certificate for this connection
      TrustManager[] trustAllCerts = new TrustManager[] {new PyPITrustManager()};

      try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());

        final HttpConfigurable settings = HttpConfigurable.getInstance();
        con = settings.openConnection(PYPI_LIST_URL);
        if (con instanceof HttpsURLConnection) {
          ((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        if (auth != null) {
          con.setRequestProperty("Authorization", "Basic " + auth);
        }
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        out.close();
        return con.getInputStream();
      } catch (NoSuchAlgorithmException e) {
        LOG.warn(e.getMessage());
      } catch (KeyManagementException e) {
        LOG.warn(e.getMessage());
      }
      return super.sendXmlRpc(request);
    }
Beispiel #19
0
 /**
  * Do the encryption
  *
  * @param plaintext
  * @param inputLen
  * @param key
  * @param iv
  * @return
  */
 private static byte[] seafileEncrypt(
     @NonNull byte[] plaintext, int inputLen, @NonNull SecretKey key, @NonNull byte[] iv) {
   try {
     Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
     IvParameterSpec ivParams = new IvParameterSpec(iv);
     cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
     return cipher.doFinal(plaintext, 0, inputLen);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     Log.e(TAG, "NoSuchAlgorithmException " + e.getMessage());
     return null;
   } catch (InvalidKeyException e) {
     e.printStackTrace();
     Log.e(TAG, "InvalidKeyException " + e.getMessage());
     return null;
   } catch (InvalidAlgorithmParameterException e) {
     e.printStackTrace();
     Log.e(TAG, "InvalidAlgorithmParameterException " + e.getMessage());
     return null;
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
     Log.e(TAG, "NoSuchPaddingException " + e.getMessage());
     return null;
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
     Log.e(TAG, "IllegalBlockSizeException " + e.getMessage());
     return null;
   } catch (BadPaddingException e) {
     e.printStackTrace();
     Log.e(TAG, "seafileEncrypt BadPaddingException " + e.getMessage());
     return null;
   }
 }
  /**
   * Encode the user ID in a secure cookie.
   *
   * @param userId
   * @return
   */
  String encodeCookie(String userId, String tokenType) {
    if (userId == null) {
      return null;
    }
    if (clusterCookieServer != null) {
      return clusterCookieServer.encodeCookie(userId);
    } else {
      long expires = System.currentTimeMillis() + ttl;
      SecureCookie secretKeyHolder = tokenStore.getActiveToken();

      try {
        return secretKeyHolder.encode(expires, userId, tokenType);
      } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
      } catch (InvalidKeyException e) {
        LOG.error(e.getMessage(), e);
      } catch (IllegalStateException e) {
        LOG.error(e.getMessage(), e);
      } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
      } catch (SecureCookieException e) {
        if (e.isError()) {
          LOG.error(e.getMessage(), e);
        } else {
          LOG.info(e.getMessage(), e);
        }
      }
      return null;
    }
  }
Beispiel #21
0
  static String doHash(
      final String input, final int hashCount, final FormatType formatType, final VERSION version)
      throws IllegalStateException {
    final String algorithm = supportedFormats.get(formatType);
    final MessageDigest md;
    try {
      md = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(
          "unable to load " + algorithm + " message digest algorithm: " + e.getMessage());
    }

    byte[] hashedBytes = input.getBytes();
    switch (version) {
      case A:
        hashedBytes = md.digest(hashedBytes);
        return Base64Util.encodeBytes(hashedBytes);

      case B:
        for (int i = 0; i < hashCount; i++) {
          hashedBytes = md.digest(hashedBytes);
        }
        return Base64Util.encodeBytes(hashedBytes);

      default:
        throw new IllegalStateException("unexpected version enum in hash method");
    }
  }
Beispiel #22
0
 public String desencripta(byte[] message) throws EncriptaException {
   try {
     final MessageDigest md = MessageDigest.getInstance("md5");
     final byte[] digestOfPassword = md.digest(clave.getBytes("utf-8"));
     final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
     for (int j = 0, k = 16; j < 8; ) {
       keyBytes[k++] = keyBytes[j++];
     }
     final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
     final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
     final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
     decipher.init(Cipher.DECRYPT_MODE, key, iv);
     final byte[] plainText = decipher.doFinal(message);
     return new String(plainText, "UTF-8");
   } catch (NoSuchAlgorithmException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (UnsupportedEncodingException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (NoSuchPaddingException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (InvalidKeyException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (InvalidAlgorithmParameterException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (IllegalBlockSizeException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (BadPaddingException ex) {
     throw new EncriptaException(ex.getMessage());
   }
 }
  private EasySSLSocketFactory() {
    super();
    TrustManager[] tm =
        new TrustManager[] {
          new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
              // do nothing
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
              // do nothing
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
            }
          }
        };
    try {
      this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
      this.sslcontext.init(null, tm, new SecureRandom());
      this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
      Log.e(this.getClass().getName(), e.getMessage());
    } catch (KeyManagementException e) {
      Log.e(this.getClass().getName(), e.getMessage());
    }
  }
Beispiel #24
0
 @Test
 public void testGetMD5() {
   try {
     assertTrue(MiscUtil.getMd5("What I got").equals("571299b6fdd88df44bb5c0534910dfba"));
   } catch (NoSuchAlgorithmException e) {
     fail("Exception " + e.getMessage() + " thrown.");
   }
 }
Beispiel #25
0
 /**
  * Create a new Key Derivation Function.
  *
  * @throws GeneralSecurityException
  */
 public KDF() throws GeneralSecurityException {
   try {
     md = MessageDigest.getInstance("SHA1");
     keyLength = 16;
   } catch (NoSuchAlgorithmException ex) {
     logger.error(ex.getMessage(), ex);
     throw new GeneralSecurityException(ex);
   }
 }
Beispiel #26
0
 public KeyPairGenerator createKeyPairGenerator(String algorithm) throws GeneralSecurityException {
   try {
     return helper.createKeyPairGenerator(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new GeneralSecurityException("cannot find algorithm: " + e.getMessage());
   } catch (NoSuchProviderException e) {
     throw new GeneralSecurityException("cannot find provider: " + e.getMessage());
   }
 }
Beispiel #27
0
 KeyFactory createKeyFactory(String algorithm) throws GeneralSecurityException, PGPException {
   try {
     return helper.createKeyFactory(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot find algorithm: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot find provider: " + e.getMessage(), e);
   }
 }
Beispiel #28
0
 private Signature createSignature(String cipherName) throws PGPException {
   try {
     return helper.createSignature(cipherName);
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot create signature: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot create signature: " + e.getMessage(), e);
   }
 }
Beispiel #29
0
 public static SecretKey getSecretKey() throws EncryptionException {
   SecretKey key = null;
   try {
     key = KeyGenerator.getInstance(ALGO).generateKey();
   } catch (NoSuchAlgorithmException e) {
     throw new EncryptionException("Cannot generate a secret key" + '\n' + e.getMessage());
   }
   return key;
 }
 public void deleteFSSFProfileDomainByUNameIdx(
     CFSecurityAuthorization Authorization,
     long argTenantId,
     long argFSSFProfileId,
     String argName) {
   final String S_ProcName = "deleteFSSFProfileDomainByUNameIdx";
   String rqst =
       CFFreeSwitchXMsgSchemaMessageFormatter.formatRqstXmlPreamble()
           + "\n"
           + "\t"
           + CFFreeSwitchXMsgFSSFProfileDomainMessageFormatter
               .formatFSSFProfileDomainRqstDeleteByUNameIdx(
                   "\n\t\t\t", argTenantId, argFSSFProfileId, argName)
           + "\n"
           + CFFreeSwitchXMsgSchemaMessageFormatter.formatRqstXmlPostamble();
   try {
     schema.getCFTipClientHandler().issueAppRequest(rqst);
   } catch (BadPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught BadPaddingException - " + e.getMessage(), e);
   } catch (IllegalBlockSizeException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught IllegalBlockSizeException - " + e.getMessage(), e);
   } catch (InvalidKeyException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught InvalidKeyException - " + e.getMessage(), e);
   } catch (NoSuchAlgorithmException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
   } catch (InvalidAlgorithmParameterException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(),
             S_ProcName,
             "Caught InvalidAlgorithmParameterException - " + e.getMessage(),
             e);
   } catch (NoSuchPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchPaddingException - " + e.getMessage(), e);
   }
   ICFTipResponseHandler responseHandler = schema.getCFTipClientHandler().getResponseHandler();
   CFLibRuntimeException exceptionRaised = responseHandler.getExceptionRaised();
   if (exceptionRaised != null) {
     throw exceptionRaised;
   }
   boolean deleted = responseHandler.getDeleted();
   if (!deleted) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Server did not respond with a Deleted message");
   }
 }