Java Code Examples for java.security.NoSuchAlgorithmException#printStackTrace()

The following examples show how to use java.security.NoSuchAlgorithmException#printStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CommonUtil.java    From homeassist with Apache License 2.0 6 votes vote down vote up
public static String md5(final String s) {
    final String MD5 = "MD5";
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 2
Source File: Hash.java    From Encryption with Apache License 2.0 6 votes vote down vote up
/**
 * Converting String to sha384 hash
 */
public String sha384(String message){
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-384");

        byte[] hash = digest.digest(message.getBytes());

        Formatter formatter = new Formatter();

        for (byte b : hash) {
            formatter.format("%02x", b);
        }

        return formatter.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 3
Source File: authority1.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public boolean is_public_key_type_exist(types.public_key_type publicKeyType) {
        for (ArrayList key : key_auths) {


            if (key.get(0).getClass() != types.public_key_type.class) {
                String pub = (String) key.get(0);

                try {
                    key.set(0, new types.public_key_type(pub));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }

            if (key.get(0).equals(publicKeyType)) {
                return true;
            }
        }
        return false;

//        return key_auths.containsKey(publicKeyType);
    }
 
Example 4
Source File: MD5Util.java    From auto-subtitle-tool with GNU General Public License v2.0 6 votes vote down vote up
public static String crypt(String str) {
    if (str == null || str.length() == 0) {
        throw new IllegalArgumentException("String to encript cannot be null or zero length");
    }
    StringBuffer hexString = new StringBuffer();
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        byte[] hash = md.digest();
        for (int i = 0; i < hash.length; i++) {
            if ((0xff & hash[i]) < 0x10) {
                hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
            } else {
                hexString.append(Integer.toHexString(0xFF & hash[i]));
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return hexString.toString();
}
 
Example 5
Source File: SignatureUtils.java    From OpenHub with GNU General Public License v3.0 6 votes vote down vote up
private static String encryptionMD5(byte[] byteStr) throws Exception {
    MessageDigest messageDigest = null;
    StringBuffer md5StrBuff = new StringBuffer();
    try {
        messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(byteStr);
        byte[] byteArray = messageDigest.digest();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
            if(i != byteArray.length - 1){
                md5StrBuff.append(":");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return md5StrBuff.toString().toUpperCase();
}
 
Example 6
Source File: TestDeserialization.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void main(Provider p) throws Exception {
    // Skip this test for providers not found by java.security.Security
    if (Security.getProvider(p.getName()) != p) {
        System.out.println("Skip test for provider " + p.getName());
        return;
    }
    SecureRandom r;
    try {
        r = SecureRandom.getInstance("PKCS11", p);
        System.out.println("SecureRandom instance " + r);
    } catch (NoSuchAlgorithmException e) {
        System.out.println("Provider " + p +
                           " does not support SecureRandom, skipping");
        e.printStackTrace();
        return;
    }
    r.setSeed(System.currentTimeMillis());
    byte[] buf = new byte[16];
    byte[] ser = toByteArray(r);
    System.out.println("Serialized Len = " + ser.length);
    SecureRandom r2 = fromByteArray(ser);
    System.out.println("Deserialized into " + r2);
    r2.nextBytes(buf);
    System.out.println("Done");
}
 
Example 7
Source File: MD5.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
public static String MD5Hash(String s) {
       MessageDigest m = null;

       try {
               m = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
               e.printStackTrace();
               return "";
       }

       m.update(s.getBytes(),0,s.length());
       String hash = new BigInteger(1, m.digest()).toString(16);
       return hash;
}
 
Example 8
Source File: AES128ECBPKCS5.java    From HttpProxy with MIT License 5 votes vote down vote up
/**
 * 由keyStr经过SHA256再取128bit作为秘钥
 * 这里SHA-256也可以换成SHA-1
 * @param keyStr
 * @return
 */
public static byte[] getKey(String keyStr){
    byte[] raw=keyStr.getBytes(CHARSET);
    MessageDigest sha = null;
    try {
        sha = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] key = sha.digest(raw);
    key = Arrays.copyOf(key, 16); // use only first 128 bit
    return key;
}
 
Example 9
Source File: CryptoUtils.java    From kotlogram with MIT License 5 votes vote down vote up
@Override
protected MessageDigest initialValue() {
    MessageDigest crypt = null;
    try {
        crypt = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return crypt;
}
 
Example 10
Source File: HTTPRequestResource.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
public HTTPRequestResource(MetaData metaData, 
		ResourceContainer container, HttpRequest request,
		boolean forceCheck) {
	super(metaData,container);
	this.request = request;

	MetaData message = metaData.createChild(HTTP_REQUEST_MESSAGE);

	message.putString(HTTP_MESSAGE_METHOD,request.getMessage().getMethodString());
	message.putString(HTTP_MESSAGE_PATH,request.getMessage().getPath());
	message.putString(HTTP_MESSAGE_VERSION,request.getMessage().getVersionString());

	metaData.putLong(HTTP_HEADERS_LENGTH,request.getHeaderBytes());

	if(request.getHeaders().isCorrupt()) {
		metaData.putBoolean(HTTP_HEADERS_CORRUPT,true);
	}

	MetaData headers = metaData.createChild(HTTP_HEADERS_LIST);
	for(HttpHeader h : request.getHeaders()) {
		headers.putString(h.getName(),h.getValue());
		// TODO: handle non-empty request entity (put/post)
	}

	countingIS = new CountingInputStream(request);
	try {
		digIS = 
			new DigestInputStream(countingIS,
					MessageDigest.getInstance("sha1"));
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
}
 
Example 11
Source File: MD5.java    From sdudoc with MIT License 5 votes vote down vote up
public static String md5(String message) {
	MessageDigest md = null;  
       try {  
           md = MessageDigest.getInstance("md5");  
           md.update(message.getBytes());  
           byte[] md5Bytes = md.digest();  
           return bytes2Hex(md5Bytes);  
       } catch (NoSuchAlgorithmException e) {  
           e.printStackTrace();  
       }  
	return "";
}
 
Example 12
Source File: SketchMD5Utils.java    From sketch with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public MessageDigest newObject() {
    try {
        return MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 13
Source File: NBTHandler.java    From wailanbt with MIT License 5 votes vote down vote up
private static String MD5(String string) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(string.getBytes());
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source File: MD5Util.java    From AndroidBase with Apache License 2.0 5 votes vote down vote up
public static byte[] md5(byte[] bytes) {
    try {
        MessageDigest digest = getDigest("MD5");
        digest.update(bytes);
        return digest.digest();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 15
Source File: CryptoUtils.java    From kotlogram with MIT License 5 votes vote down vote up
@Override
protected MessageDigest initialValue() {
    MessageDigest crypt = null;
    try {
        crypt = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return crypt;
}
 
Example 16
Source File: VenvyMD5Util.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 字符串 SHA 加密
 *
 * @return
 */
private static String SHA(final String strText, final String strType) {
    // 返回值
    String strResult = null;

    // 是否是有效字符串
    if (strText != null && strText.length() > 0) {
        try {
            // SHA 加密开始
            // 创建加密对象 并傳入加密類型
            MessageDigest messageDigest = MessageDigest.getInstance(strType);
            // 传入要加密的字符串
            messageDigest.update(strText.getBytes());
            // 得到 byte 類型结果
            byte byteBuffer[] = messageDigest.digest();

            // 將 byte 轉換爲 string
            StringBuffer strHexString = new StringBuffer();
            // 遍歷 byte buffer
            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            // 得到返回結果
            strResult = strHexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    return strResult;
}
 
Example 17
Source File: EncryptionUtil.java    From FastLogin with MIT License 5 votes vote down vote up
/**
 * Generate the server id based on client and server data.
 *
 * @param sessionId    session for the current login attempt
 * @param sharedSecret shared secret between the client and the server
 * @param publicKey    public key of the server
 * @return the server id formatted as a hexadecimal string.
 */
public static String getServerIdHashString(String sessionId, SecretKey sharedSecret, PublicKey publicKey) {
    // found in LoginListener
    try {
        byte[] serverHash = getServerIdHash(sessionId, publicKey, sharedSecret);
        return (new BigInteger(serverHash)).toString(16);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return "";
}
 
Example 18
Source File: Security.java    From chat-socket with MIT License 5 votes vote down vote up
private static String convertToSHA1(byte[] bytes) {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
        return bytesToHexString(md.digest(bytes));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 19
Source File: AESPBEWrapper.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    boolean isUnlimited;
    try {
        isUnlimited =
            (Cipher.getMaxAllowedKeyLength(this.algo) == Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException nsae) {
        out.println("Got unexpected exception for " + this.algo);
        nsae.printStackTrace(out);
        return false;
    }
    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, this.key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.DECRYPT_MODE, this.key, pbeParams);
        }

        if (this.algo.endsWith("AES_256") && !isUnlimited) {
            out.print("Expected exception not thrown for " + this.algo);
            return false;
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        if ((ex instanceof InvalidKeyException)
                && this.algo.endsWith("AES_256") && !isUnlimited) {
            out.println("Expected InvalidKeyException thrown");
            return true;
        } else {
            out.println("Got unexpected exception for " + algo);
            ex.printStackTrace(out);
            return false;
        }
    }
}
 
Example 20
Source File: UDIDGenerator.java    From android-commons with Apache License 2.0 4 votes vote down vote up
public static String generateUDID(Context context) {
  //1 compute IMEI
  TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  String m_szImei = TelephonyMgr.getDeviceId(); // Requires READ_PHONE_STATE

  //2 compute DEVICE ID
  String m_szDevIDShort = "35" + //we make this look like a valid IMEI
      Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
      Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
      Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
      Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
      Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
      Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
      Build.USER.length() % 10; //13 digits
  //3 android ID - unreliable
  String m_szAndroidID = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

  //4 wifi manager, read MAC address - requires  android.permission.ACCESS_WIFI_STATE or comes as null
  WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();


  //6 SUM THE IDs
  String m_szLongID = m_szImei + m_szDevIDShort + m_szAndroidID + m_szWLANMAC;
  MessageDigest m = null;
  try {
    m = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  m.update(m_szLongID.getBytes(), 0, m_szLongID.length());
  byte p_md5Data[] = m.digest();

  String m_szUniqueID = new String();
  for (int i = 0; i < p_md5Data.length; i++) {
    int b = (0xFF & p_md5Data[i]);
    // if it is a single digit, make sure it have 0 in front (proper padding)
    if (b <= 0xF) m_szUniqueID += "0";
    // add number to string
    m_szUniqueID += Integer.toHexString(b);
  }
  m_szUniqueID = m_szUniqueID.toUpperCase();
  return m_szUniqueID;
}