Example #1
1
 private static TerminalFactory loadFactory(String pn, String type)
     throws NoSuchAlgorithmException {
   TerminalFactory tf = null;
   try {
     Class<?> cls = Class.forName(pn);
     Provider p = (Provider) cls.getConstructor().newInstance();
     tf = TerminalFactory.getInstance(type == null ? "PC/SC" : type, null, p);
   } catch (ClassNotFoundException
       | InstantiationException
       | IllegalAccessException
       | IllegalArgumentException
       | InvocationTargetException
       | NoSuchMethodException
       | SecurityException e) {
     throw new RuntimeException("Could not load " + pn, e);
   } catch (NoSuchAlgorithmException e) {
     if (e.getCause() != null) {
       Class<?> cause = e.getCause().getClass();
       if (cause.equals(java.lang.UnsupportedOperationException.class)) {
         throw new NoSuchAlgorithmException(e.getCause().getMessage());
       }
       if (cause.equals(java.lang.UnsatisfiedLinkError.class)) {
         throw new NoSuchAlgorithmException(e.getCause().getMessage());
       }
     }
     throw e;
   }
   return tf;
 }
  public static String printKeyHash(Activity context) {
    PackageInfo packageInfo;
    String key = null;
    try {
      // getting application package name, as defined in manifest
      String packageName = context.getApplicationContext().getPackageName();

      // Retriving package info
      packageInfo =
          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);

      Log.e("Package Name=", context.getApplicationContext().getPackageName());

      for (Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));

        // String key = new String(Base64.encodeBytes(md.digest()));
        Log.e("Key Hash=", key);
      }
    } catch (PackageManager.NameNotFoundException e1) {
      Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
      Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
      Log.e("Exception", e.toString());
    }

    return key;
  }
Example #3
0
  /**
   * The algorithm function takes in an input and generates a unique token for that input.
   *
   * <p>Note This function can be overridden to provide a custom implementation of the algorithm.
   *
   * @param input A input of type String for which a token has to be generated.
   * @return returns the Unique token generated using this algorithm.
   */
  public String algorithm(String input) {

    String md5 = null;

    if (null == input) {
      return null;
    }

    try {

      // Create MessageDigest object for MD5
      MessageDigest digest = MessageDigest.getInstance("MD5");

      // Update input string in message digest
      digest.update(input.getBytes(), 0, input.length());

      // Converts message digest value in base 16 (hex)
      md5 = new BigInteger(1, digest.digest()).toString(16);

    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    String token = "";
    final String[] segments = md5.split(String.format("(?s)(?<=\\G.{%d})", 4));
    for (int i = 0; i < segments.length - 1; i++) {
      token += segments[i] + "-";
    }
    token += segments[segments.length - 1];
    return token;
  }
Example #4
0
  private FSInputStream(SVNDeltaCombiner combiner, FSRepresentation representation, FSFS owner)
      throws SVNException {
    myCombiner = combiner;
    myChunkIndex = 0;
    isChecksumFinalized = false;
    myHexChecksum = representation.getMD5HexDigest();
    myOffset = 0;
    myLength = representation.getExpandedSize();
    try {
      myDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException nsae) {
      SVNErrorMessage err =
          SVNErrorMessage.create(
              SVNErrorCode.IO_ERROR,
              "MD5 implementation not found: {0}",
              nsae.getLocalizedMessage());
      SVNErrorManager.error(err, nsae, SVNLogType.FSFS);
    }

    try {
      buildRepresentationList(representation, myRepStateList, owner);
    } catch (SVNException svne) {
      /*
       * Something terrible has happened while building rep list, need to
       * close any files still opened
       */
      close();
      throw svne;
    }
  }
  /**
   * 加密(使用DES算法)
   *
   * @param txt 需要加密的文本
   * @param key 密钥
   * @return 成功加密的文本
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   * @throws NoSuchPaddingException
   * @throws IllegalBlockSizeException
   * @throws BadPaddingException
   */
  private static String enCrypto(String txt, String key)
      throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException {
    StringBuffer sb = new StringBuffer();
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
    SecretKeyFactory skeyFactory = null;
    Cipher cipher = null;
    try {
      skeyFactory = SecretKeyFactory.getInstance("DES");
      cipher = Cipher.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey deskey = skeyFactory != null ? skeyFactory.generateSecret(desKeySpec) : null;
    if (cipher != null) {
      cipher.init(Cipher.ENCRYPT_MODE, deskey);
    }
    byte[] cipherText = cipher != null ? cipher.doFinal(txt.getBytes()) : new byte[0];
    for (int n = 0; n < cipherText.length; n++) {
      String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF));

      if (stmp.length() == 1) {
        sb.append("0" + stmp);
      } else {
        sb.append(stmp);
      }
    }
    return sb.toString().toUpperCase();
  }
Example #6
0
 static {
   try {
     messageDigest = MessageDigest.getInstance("SHA1");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
 }
Example #7
0
  public static String getFileMd5(String sourceDir) {
    try {
      File file = new File(sourceDir);
      FileInputStream fis = new FileInputStream(file);
      byte[] buf = new byte[1024];
      int len = -1;

      // 获取数字摘要
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      while ((len = fis.read(buf)) != -1) {
        messageDigest.update(buf, 0, len);
      }
      byte[] result = messageDigest.digest();
      StringBuffer sb = new StringBuffer();
      for (byte b : result) {
        int i = b & 0xff;
        String hexString = Integer.toHexString(i);
        if (hexString.length() < 2) {
          hexString = "0" + hexString;
        }
        sb.append(hexString);
      }
      return sb.toString();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #8
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());
    }
  }
 public UrlList getUrlList(String url) {
   UrlList urlList = null;
   try {
     String key = Hash.hashKey(url);
     GetObjectRequest req = new GetObjectRequest(bucketName, key);
     S3Object s3Object = s3client.getObject(req);
     InputStream objectData = s3Object.getObjectContent();
     BufferedReader reader = new BufferedReader(new InputStreamReader(objectData));
     StringBuilder s3Content = new StringBuilder();
     String line;
     while ((line = reader.readLine()) != null) {
       s3Content.append(line + "\r\n");
     }
     reader.close();
     objectData.close();
     ObjectMapper mapper = new ObjectMapper();
     mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
     mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
     urlList = mapper.readValue(s3Content.toString(), UrlList.class);
   } catch (AmazonS3Exception ase) {
     System.out.println("S3UrlListDA : document does not exist");
     ase.printStackTrace();
   } catch (IOException e) {
     System.out.println("S3UrlListDA : IOException while fetching document from S3");
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return urlList;
 }
Example #10
0
  private KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
      if (bksFile == null || password == null) return null;

      KeyStore clientKeyStore = KeyStore.getInstance("BKS");
      clientKeyStore.load(bksFile, password.toCharArray());
      KeyManagerFactory keyManagerFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(clientKeyStore, password.toCharArray());
      return keyManagerFactory.getKeyManagers();

    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  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);
    }
  }
Example #12
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
      RSACryptoProvider rsa = new RSACryptoProvider();
      byte[] data = rsa.Encrypt("Michael");
      System.out.println(new String(data));
      System.out.println(rsa.Decrypt(data));

    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (BadPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private SSLSocketFactory createTrustedSocketFactory() {
    try {
      final SSLContext context = SSLContext.getInstance("ssl");
      final X509TrustManager trustManager =
          new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {}

            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {}

            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
            }
          };
      context.init(null, new TrustManager[] {trustManager}, null);
      return context.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    }
    return null;
  }
 public static Map<String, String> sign(String jsapi_ticket, String url) {
   Map<String, String> ret = new HashMap<String, String>();
   String nonce_str = create_nonce_str();
   String timestamp = create_timestamp();
   String str;
   String signature = "";
   str =
       "jsapi_ticket="
           + jsapi_ticket
           + "&noncestr="
           + nonce_str
           + "&timestamp="
           + timestamp
           + "&url="
           + url;
   try {
     MessageDigest crypt = MessageDigest.getInstance("SHA-1");
     crypt.reset();
     crypt.update(str.getBytes("UTF-8"));
     signature = byteToHex(crypt.digest());
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   ret.put("url", url);
   ret.put("jsapi_ticket", jsapi_ticket);
   ret.put("nonceStr", nonce_str);
   ret.put("timestamp", timestamp);
   ret.put("signature", signature);
   return ret;
 }
 /**
  * Key store 类型HttpClient
  *
  * @param keystore keystore
  * @param keyPassword keyPassword
  * @param supportedProtocols supportedProtocols
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return CloseableHttpClient
  */
 public static CloseableHttpClient createKeyMaterialHttpClient(
     KeyStore keystore,
     String keyPassword,
     String[] supportedProtocols,
     int timeout,
     int retryExecutionCount) {
   try {
     SSLContext sslContext =
         SSLContexts.custom()
             .useSSL()
             .loadKeyMaterial(keystore, keyPassword.toCharArray())
             .build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext,
             supportedProtocols,
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     return HttpClientBuilder.create()
         .setDefaultSocketConfig(socketConfig)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #16
0
 public static CloseableHttpClient createSSLClientDefault() {
   try {
     SSLContext sslContext =
         new SSLContextBuilder()
             .loadTrustMaterial(
                 null,
                 new TrustStrategy() {
                   // 信任所有
                   public boolean isTrusted(X509Certificate[] chain, String authType)
                       throws CertificateException {
                     return true;
                   }
                 })
             .build();
     SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
     return HttpClients.custom().setSSLSocketFactory(sslsf).build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return HttpClients.createDefault();
 }
 protected MessageDigest initialValue() {
   try {
     return MessageDigest.getInstance("MD5");
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalStateException(e.getMessage(), e);
   }
 }
Example #18
0
  public static String getCertFingerprint(Context context) {
    try {
      @SuppressLint("PackageManagerGetSignatures")
      Signature[] sigs =
          context
              .getPackageManager()
              .getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES)
              .signatures;

      if (sigs.length == 0) {
        return "ERROR: NO SIGNATURE.";
      } else if (sigs.length > 1) {
        return "ERROR: MULTIPLE SIGNATURES";
      }
      byte[] digest = MessageDigest.getInstance("SHA1").digest(sigs[0].toByteArray());
      StringBuilder hexString = new StringBuilder();
      for (int i = 0; i < digest.length; ++i) {
        if (i > 0) {
          hexString.append(":");
        }
        byteToString(hexString, digest[i]);
      }
      return hexString.toString();

    } catch (PackageManager.NameNotFoundException ex) {
      ex.printStackTrace();
      return "(ERROR: package not found)";
    } catch (NoSuchAlgorithmException ex) {
      ex.printStackTrace();
      return "(ERROR: SHA1 algorithm not found)";
    }
  }
Example #19
0
  /**
   * Create a STPR STPR = T|Comm(L_1, r^1_W)|...|Comm(L_n, r^n_W)
   *
   * @param aStampContext
   * @param location location L_1
   * @param time Preq time T
   * @return STPR
   */
  private static byte[] createSTPR(WitnessContext aStampContext, byte location[], byte time[]) {

    BigInteger rw = aStampContext.getEPRandomW();

    String locString = new String(location);
    Location loc = new Location(locString);
    short levelCount = (short) loc.getLevelCount();

    LinkedList<BigInteger> rws = new LinkedList<BigInteger>();
    try {
      rws = CryptoUtil.getHashChain(rw, levelCount);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    ArrayList<byte[]> locComms = new ArrayList<byte[]>();
    for (int i = 0; i < levelCount; i++) {
      byte[] locComm = {};
      try {
        locComm = CryptoUtil.getCommitment(loc.getLevel(i).getBytes(), rws.get(i)).toByteArray();
      } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      locComms.add(locComm);
    }

    return MessageUtil.createMessageFromArray(locComms);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bm = null;
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen;
    try {
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(keyStart);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();

      // encrypt
      byte[] encryptedData = encrypt(key, b);
      // decrypt
      byte[] decryptedData = decrypt(key, encryptedData);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    } catch (Exception e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    }
  }
Example #21
0
 public static String getMD5(File file) {
   FileInputStream fileInputStream = null;
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     fileInputStream = new FileInputStream(file);
     byte[] buffer = new byte[2048];
     int length = -1;
     long s = System.currentTimeMillis();
     while ((length = fileInputStream.read(buffer)) != -1) {
       md.update(buffer, 0, length);
     }
     byte[] b = md.digest();
     return byteToHexString(b);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     return null;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   } finally {
     try {
       fileInputStream.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Example #22
0
  /**
   * 对报文进行采用MD5进行hmac签名
   *
   * @param aValue - 字符�?
   * @param aKey - 密钥
   * @param encoding - 字符串编码方�?
   * @return - 签名结果,hex字符�?
   */
  public static String hmacSign(String aValue, String aKey, String encoding) {
    byte k_ipad[] = new byte[64];
    byte k_opad[] = new byte[64];
    byte keyb[];
    byte value[];
    try {
      keyb = aKey.getBytes(encoding);
      value = aValue.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
      keyb = aKey.getBytes();
      value = aValue.getBytes();
    }
    Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
    Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
    for (int i = 0; i < keyb.length; i++) {
      k_ipad[i] = (byte) (keyb[i] ^ 0x36);
      k_opad[i] = (byte) (keyb[i] ^ 0x5c);
    }

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    }
    md.update(k_ipad);
    md.update(value);
    byte dg[] = md.digest();
    md.reset();
    md.update(k_opad);
    md.update(dg, 0, 16);
    dg = md.digest();
    return ConvertUtils.toHex(dg);
  }
Example #23
0
 private String getFileMD5String(File file, int bufferSize) {
   FileInputStream fileInputStream = null;
   byte[] buffer = new byte[bufferSize];
   try {
     MessageDigest targetMD5 = MessageDigest.getInstance("MD5");
     fileInputStream = new FileInputStream(file);
     int len;
     while ((len = fileInputStream.read(buffer)) != -1) {
       targetMD5.update(buffer, 0, len);
     }
     return DataSwitch.bytesToHexString(targetMD5.digest()).toUpperCase();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } finally {
     if (fileInputStream != null)
       try {
         fileInputStream.close();
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
   }
   return null;
 }
Example #24
0
  // generates a SHA-1 hash for any string
  public static String getHash(String stringToHash) {

    MessageDigest digest = null;
    try {
      digest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    byte[] result = null;

    try {
      result = digest.digest(stringToHash.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    StringBuilder sb = new StringBuilder();

    for (byte b : result) {
      sb.append(String.format("%02X", b));
    }

    String messageDigest = sb.toString();
    return messageDigest;
  }
    @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);
    }
  public static synchronized int generateMD5Id(Object... object) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos;
      oos = new ObjectOutputStream(baos);

      for (Object x : object) {
        if (x == null) oos.writeChars("null");
        else if (x instanceof Integer) oos.writeInt((Integer) x);
        else if (x instanceof String) oos.writeChars((String) x);
        else if (x instanceof Double) oos.writeDouble((Double) x);
        else if (x instanceof Class) oos.writeChars(((Class<?>) x).getName());
      }

      oos.close();
      MessageDigest m = MessageDigest.getInstance("MD5");
      m.update(baos.toByteArray());
      BigInteger testObjectHash = new BigInteger(m.digest());
      return testObjectHash.intValue();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return 0;
  }
Example #27
0
  public static String md5(String plainText) {
    String str;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(plainText.getBytes());
      byte b[] = md.digest();

      int i;

      StringBuffer buf = new StringBuffer("");
      for (int offset = 0; offset < b.length; offset++) {
        i = b[offset];
        if (i < 0) i += 256;
        if (i < 16) buf.append("0");
        buf.append(Integer.toHexString(i));
      }
      str = buf.toString();
      // System.out.println("result: " + buf.toString());// 32位的加密
      // System.out.println("result: " + buf.toString().substring(8,
      // 24));// 16位的加密
      return str;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
  }
 /**
  * @param maxTotal maxTotal
  * @param maxPerRoute maxPerRoute
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return
  */
 public static CloseableHttpClient createHttpClient(
     int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) {
   try {
     SSLContext sslContext = SSLContexts.custom().useSSL().build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
         new PoolingHttpClientConnectionManager();
     poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
     poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig);
     return HttpClientBuilder.create()
         .setConnectionManager(poolingHttpClientConnectionManager)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #29
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;
  }
Example #30
0
 /**
  * 加密
  *
  * @param content 需要加密的内容
  * @param password 加密密码
  * @return
  */
 public static byte[] encryptAES(String content, String password) {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(password.getBytes()));
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, key); // 初始化
     byte[] result = cipher.doFinal(byteContent);
     return result; // 加密
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return null;
 }