コード例 #1
0
ファイル: Tools.java プロジェクト: zzh1307/Xunlian
 private void init() {
   try {
     /**
      * 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个 getInstance 类方法构造的。 KeyGenerator
      * 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一 KeyGenerator 对象来生成进一步的密钥。 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。
      * 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。 此 KeyGenerator 类中有一个 init
      * 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的 init 方法, 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源
      * (如果安装的提供程序都不提供 SecureRandom 实现,则使用系统提供的随机源)。 此 KeyGenerator 类还提供一个只带随机源参数的 inti 方法。
      * 因为调用上述与算法无关的 init 方法时未指定其他参数, 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化
      * 在已经存在特定于算法的参数集的情况下, 有两个具有 AlgorithmParameterSpec 参数的 init 方法。 其中一个方法还有一个 SecureRandom 参数,
      * 而另一个方法将已安装的高优先级提供程序的 SecureRandom 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。
      * 如果客户端没有显式地初始化 KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。
      */
     keyGen = KeyGenerator.getInstance("AES");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   // 初始化此密钥生成器,使其具有确定的密钥长度。
   keyGen.init(128); // 128位的AES加密
   try {
     // 生成一个实现指定转换的 Cipher 对象。
     cipher = Cipher.getInstance(algorithmStr);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   }
   // 标识已经初始化过了的字段
   isInited = true;
 }
コード例 #2
0
ファイル: StampMessage.java プロジェクト: johndoe2012/STAMP
  /**
   * 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);
  }
コード例 #3
0
  public static byte[] passwordEncrypt(char[] password, byte[] plaintext) {
    byte[] salt = new byte[8];
    Random random = new Random();
    random.nextBytes(salt);

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = null;
    try {
      keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey key = null;
    try {
      key = keyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    }
    try {
      cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }

    byte[] ciphertext = new byte[0];
    try {
      ciphertext = cipher.doFinal(plaintext);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      baos.write(salt);
      baos.write(ciphertext);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return baos.toByteArray();
  }
コード例 #4
0
ファイル: StampMessage.java プロジェクト: johndoe2012/STAMP
  /**
   * Endorse the proof
   *
   * @param aStampContext current context
   * @param aProof proof
   * @return endorsed proof
   * @throws NoSuchAlgorithmException
   * @throws BadPaddingException
   * @throws IllegalBlockSizeException
   * @throws NoSuchPaddingException
   * @throws InvalidKeyException
   */
  private static byte[] endorseP(WitnessContext aStampContext, byte aProof[]) {

    // Sign on the proof first
    byte[] sig = {};
    try {
      sig = CryptoUtil.signDSA(aStampContext.getPriDSASelf(), aProof);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (SignatureException e) {
      e.printStackTrace();
    }

    // Include own ID in EP
    byte[] wID = aStampContext.getPubDSASelf().getEncoded();

    ArrayList<byte[]> array = new ArrayList<byte[]>();
    array.add(wID);
    array.add(aProof);
    array.add(sig);

    byte[] epContent = MessageUtil.compileMessages(array);

    // Encrypt epContent with an AES key first
    SecretKey aesKey = null;
    byte[] epEncrypted = {};
    byte[] keyEncrypted = {};
    try {
      aesKey = CryptoUtil.generateAESKey(128);
      epEncrypted = CryptoUtil.encryptAES(aesKey, epContent);
      keyEncrypted = CryptoUtil.encryptRSA(aStampContext.getPubRSACA(), aesKey.getEncoded());
    } catch (NoSuchAlgorithmException e1) {
      e1.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    ArrayList<byte[]> arrayOut = new ArrayList<byte[]>();
    arrayOut.add(epEncrypted);
    arrayOut.add(keyEncrypted);

    return MessageUtil.compileMessages(arrayOut);
  }
コード例 #5
0
  public static byte[] passwordDecrypt(char[] password, byte[] ciphertext) {
    byte[] salt = new byte[8];
    ByteArrayInputStream bais = new ByteArrayInputStream(ciphertext);
    bais.read(salt, 0, 8);

    byte[] remainingCiphertext = new byte[ciphertext.length - 8];
    bais.read(remainingCiphertext, 0, ciphertext.length - 8);

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = null;
    try {
      keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey secretKey = null;
    try {
      secretKey = keyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }

    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);

    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    }
    try {
      cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }

    try {
      return cipher.doFinal(remainingCiphertext);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return null;
  }
コード例 #6
0
 public static String decrypt(String property) {
   SecretKeyFactory keyFactory = null;
   String retValue = null;
   try {
     keyFactory = SecretKeyFactory.getInstance(encrypteAlgorithm);
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   SecretKey key = null;
   try {
     key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
   } catch (InvalidKeySpecException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   Cipher pbeCipher = null;
   try {
     pbeCipher = Cipher.getInstance(encrypteAlgorithm);
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   try {
     pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
   } catch (InvalidKeyException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (InvalidAlgorithmParameterException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   try {
     retValue = new String(pbeCipher.doFinal(base64Decode(property)));
   } catch (IllegalBlockSizeException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (BadPaddingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return retValue;
 }
コード例 #7
0
 /**
  * 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;
 }
コード例 #8
0
  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;
  }
コード例 #9
0
 /**
  * @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;
 }
コード例 #10
0
ファイル: Digest.java プロジェクト: quzhaomei/admin
  /**
   * 对报文进行采用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);
  }
コード例 #11
0
ファイル: DeviceUtil.java プロジェクト: KhinSandar/iwomen2016
  // 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;
  }
コード例 #12
0
ファイル: DecriptTest.java プロジェクト: hx863975383/gits
 /**
  * 加密
  *
  * @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;
 }
コード例 #13
0
  @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();
    }
  }
コード例 #14
0
ファイル: Test.java プロジェクト: Yhaojing/sftpAndPdf
 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();
     }
   }
 }
コード例 #15
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;
 }
コード例 #16
0
ファイル: program.java プロジェクト: istbarp/ChatX
  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();
    }
  }
コード例 #17
0
ファイル: SignUtil.java プロジェクト: zcalyz/DBImport
  public static boolean checkSignature(String signature, String timestamp, String nonce) {
    String[] arr = new String[] {Constant.Token, timestamp, nonce};
    Arrays.sort(arr);

    StringBuilder content = new StringBuilder();
    for (int i = 0; i < arr.length; i++) {
      content.append(arr[i]);
    }

    MessageDigest md = null;
    String tmpStr = null;

    try {
      md = MessageDigest.getInstance("SHA-1");
      // 将三个参数字符串拼接成一个字符串进行sha1加密
      byte[] digest = md.digest(content.toString().getBytes());
      tmpStr = byteToStr(digest);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    content = null;
    // 将sha1加密后的字符串可与signature对比
    return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
  }
コード例 #18
0
  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;
  }
コード例 #19
0
 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;
 }
コード例 #20
0
ファイル: TokenAlgorithm.java プロジェクト: nawaf331/MDkeys
  /**
   * 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;
  }
コード例 #21
0
ファイル: TestUtil.java プロジェクト: liyiwan/-jungle
 static {
   try {
     messageDigest = MessageDigest.getInstance("SHA1");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
 }
コード例 #22
0
ファイル: AUKeyManager.java プロジェクト: soa4java/asim
  /**
   * 使用口令加密私钥(Base64编码)
   *
   * @return
   */
  public String encryptPrivateKey(String passphrase) {
    byte[] seeds = null;
    byte[] raw = mMyPrivKey.getEncoded();
    byte[] encrypted = null;

    Cipher cipher;
    try {
      seeds = getRawKey(passphrase.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(seeds, PASS_ALGO);
      cipher = Cipher.getInstance(PASS_ALGO);
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      encrypted = cipher.doFinal(raw);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
    return result;
  }
コード例 #23
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;
  }
コード例 #24
0
  /**
   * 对字符串进行 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);
  }
コード例 #25
0
ファイル: MD5Utils.java プロジェクト: Joey-Huang/MobileSafe
  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;
  }
コード例 #26
0
 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;
 }
コード例 #27
0
  /**
   * 加密(使用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();
  }
コード例 #28
0
ファイル: HttpUtil.java プロジェクト: sumekey/sms
 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();
 }
コード例 #29
0
ファイル: MD5.java プロジェクト: huluhaziqi/Canting
  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;
  }
コード例 #30
0
ファイル: SHA1.java プロジェクト: RomanBase/Inv
  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)";
    }
  }