public static void logTokens(Activity context) { // Add code to print out the key hash try { PackageInfo info = context .getPackageManager() .getPackageInfo( context.getApplicationContext().getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(signature.toByteArray()); Log.d("SHA-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT)); md = MessageDigest.getInstance("MD5"); md.update(signature.toByteArray()); Log.d("MD5-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT)); md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("SHA-Hex-From-KeyHash:::", bytesToHex(md.digest())); } } catch (NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } }
/** * 对报文进行采用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); }
private static void writeSignatureFile(Manifest manifest, SignatureOutputStream out) throws IOException, GeneralSecurityException { Manifest sf = new Manifest(); Attributes main = sf.getMainAttributes(); main.putValue("Signature-Version", "1.0"); main.putValue("Created-By", "1.0 (KApkSigner)"); BASE64Encoder base64 = new BASE64Encoder(); MessageDigest md = MessageDigest.getInstance("SHA1"); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8"); manifest.write(print); print.flush(); main.putValue("SHA1-Digest-Manifest", base64.encode(md.digest())); Map<String, Attributes> entries = manifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); Attributes sfAttr = new Attributes(); sfAttr.putValue("SHA1-Digest", base64.encode(md.digest())); sf.getEntries().put(entry.getKey(), sfAttr); } sf.write(out); if (out.size() % 1024 == 0) { out.write('\r'); out.write('\n'); } }
public byte[] hash48(byte[] in, byte[] salt1, byte[] salt2, int salt) throws CryptoException { byte[] shasig = new byte[20]; byte[] pad = new byte[4]; byte[] out = new byte[48]; int i = 0; synchronized (digestLock) { sha1.reset(); md5.reset(); for (i = 0; i < 3; i++) { for (int j = 0; j <= i; j++) { pad[j] = (byte) (salt + i); } sha1.update(pad, 0, i + 1); sha1.update(in, 0, 48); sha1.update(salt1, 0, 32); sha1.update(salt2, 0, 32); shasig = sha1.digest(); sha1.reset(); md5.update(in, 0, 48); md5.update(shasig, 0, 20); System.arraycopy(md5.digest(), 0, out, i * 16, 16); } } return out; }
public static boolean verify( byte[] signature, byte[] message, byte[] publicKey, boolean enforceCanonical) { try { if (enforceCanonical && !Curve25519.isCanonicalSignature(signature)) { Logger.logDebugMessage("Rejecting non-canonical signature"); return false; } if (enforceCanonical && !Curve25519.isCanonicalPublicKey(publicKey)) { Logger.logDebugMessage("Rejecting non-canonical public key"); return false; } byte[] Y = new byte[32]; byte[] v = new byte[32]; System.arraycopy(signature, 0, v, 0, 32); byte[] h = new byte[32]; System.arraycopy(signature, 32, h, 0, 32); Curve25519.verify(Y, v, h, publicKey); MessageDigest digest = Crypto.sha256(); byte[] m = digest.digest(message); digest.update(m); byte[] h2 = digest.digest(Y); return Arrays.equals(h, h2); } catch (RuntimeException e) { Logger.logMessage("Error in Crypto verify", e); return false; } }
/** * Generate the mask. * * @param seed source of input bytes for initial digest state * @param length length of mask to generate * @return a byte array containing a MGF1 generated mask */ public byte[] generateMask(byte[] seed, int length) { byte[] mask = new byte[length]; byte[] C = new byte[4]; int counter = 0; int hLen = digest.getDigestLength(); digest.reset(); while (counter < (length / hLen)) { ItoOSP(counter, C); digest.update(seed); digest.update(C); System.arraycopy(digest.digest(), 0, mask, counter * hLen, hLen); counter++; } if ((counter * hLen) < length) { ItoOSP(counter, C); digest.update(seed); digest.update(C); System.arraycopy(digest.digest(), 0, mask, counter * hLen, mask.length - (counter * hLen)); } return mask; }
/** * @param key * @param update_key * @return * @throws CryptoException */ public byte[] update(byte[] key, byte[] update_key) throws CryptoException { byte[] shasig = new byte[20]; byte[] update = new byte[this.keylength]; // changed from 8 - rdesktop // 1.2.0 byte[] thekey = new byte[key.length]; synchronized (digestLock) { sha1.reset(); sha1.update(update_key, 0, keylength); sha1.update(pad_54, 0, 40); sha1.update(key, 0, keylength); // changed from 8 - rdesktop // 1.2.0 shasig = sha1.digest(); sha1.reset(); md5.reset(); md5.update(update_key, 0, keylength); // changed from 8 - rdesktop // 1.2.0 md5.update(pad_92, 0, 48); md5.update(shasig, 0, 20); thekey = md5.digest(); md5.reset(); System.arraycopy(thekey, 0, update, 0, this.keylength); rc4_update.engineInitDecrypt(update); // added thekey = rc4_update.crypt(thekey, 0, this.keylength); if (this.keylength == 8) { this.make40bit(thekey); } } return thekey; }
public static String hashIt(final String salt, String data) { data = Normalizer.normalize(data, Form.NFC); final byte[] strData = data.getBytes(StandardCharsets.UTF_8); final byte[] saltData = salt.getBytes(StandardCharsets.UTF_8); final byte[] first = new byte[saltData.length + strData.length]; System.arraycopy(saltData, 0, first, 0, saltData.length); System.arraycopy(strData, 0, first, saltData.length, strData.length); MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException(e); } byte[] digest = md.digest(first); final byte[] current = new byte[saltData.length + digest.length]; for (int i = 0; i < 1000; i++) { System.arraycopy(saltData, 0, current, 0, saltData.length); System.arraycopy(digest, 0, current, saltData.length, digest.length); digest = md.digest(current); } return Base64.getEncoder().encodeToString(digest); }
/** * Encrypts given password using salt. Uses algorithm that makes password non-decryptable, because * no-one should ever be able to see passwords. Salt is used to make passwords secure against * precomputed hashes (<a href="http://en.wikipedia.org/wiki/Rainbow_table" target="_blank">see * here</a>). The reason for all this is that mostly all algorithms used for encryption are open * source. * * @param pword The password to be encrypted. * @param salt The salt to use in encryption. It should be a randomly generated number, and * preferrably of fixed length. * @return Encrypted password. */ private static byte[] getHash(String pword, byte[] salt) { byte[] input = null; try { /* * Get digester and update it with given salt. Using SHA-1 * algorithm. See: * http://docs.oracle.com/javase/7/docs/technotes/guides * /security/StandardNames.html#MessageDigest for supported * algorithms. */ MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt); /* * Digest password according to ITERATION_COUNT. See: * http://docs.oracle * .com/javase/7/docs/api/java/nio/charset/Charset.html for * supported charsets. */ input = digest.digest(pword.getBytes("UTF-8")); for (int i = 0; i < UserHandler.ITERATION_COUNT; i++) { digest.reset(); input = digest.digest(input); } } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { /* * These should never happen, as chosen algorithm and encoding are * both legit. NOTE: Be careful if you change them. */ } return input; }
public byte[] createDigest(String user, String password, String nonce) { try { String realm = "resin"; MessageDigest md = MessageDigest.getInstance("MD5"); if (user != null) md.update(user.getBytes("UTF-8")); md.update((byte) ':'); md.update(realm.getBytes("UTF-8")); md.update((byte) ':'); if (password != null) md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); md.reset(); updateHex(md, digest); md.update((byte) ':'); md.update(nonce.getBytes("UTF-8")); return md.digest(); } catch (Exception e) { throw new IllegalStateException(e); } }
@Override public HashCode hash() { done = true; return (bytes == digest.getDigestLength()) ? HashCode.fromBytesNoCopy(digest.digest()) : HashCode.fromBytesNoCopy(Arrays.copyOf(digest.digest(), bytes)); }
public static Script buildOutput(String address) { try { byte[] addressWithCheckSumAndNetworkCode = BTCUtils.decodeBase58(address); if (addressWithCheckSumAndNetworkCode[0] != 0) { throw new RuntimeException("unknown address type"); } byte[] bareAddress = new byte[20]; System.arraycopy(addressWithCheckSumAndNetworkCode, 1, bareAddress, 0, bareAddress.length); MessageDigest digestSha = MessageDigest.getInstance("SHA-256"); digestSha.update( addressWithCheckSumAndNetworkCode, 0, addressWithCheckSumAndNetworkCode.length - 4); byte[] calculatedDigest = digestSha.digest(digestSha.digest()); for (int i = 0; i < 4; i++) { if (calculatedDigest[i] != addressWithCheckSumAndNetworkCode[ addressWithCheckSumAndNetworkCode.length - 4 + i]) { throw new RuntimeException("bad address"); } } ByteArrayOutputStream buf = new ByteArrayOutputStream(25); buf.write(OP_DUP); buf.write(OP_HASH160); writeBytes(bareAddress, buf); buf.write(OP_EQUALVERIFY); buf.write(OP_CHECKSIG); return new Script(buf.toByteArray()); } catch (Exception e) { throw new RuntimeException(); } }
private boolean verifyPassword( String inputPassword, String storedPasswordHash, String storedSalt) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("MD5 is an invalid algorithm!", e); return false; } byte[] inputPasswordHash = digest.digest(inputPassword.getBytes()); digest.reset(); byte[] storedSaltHash = digest.digest(storedSalt.getBytes()); digest.reset(); byte[] finalHash = digest.digest( new StringBuilder() .append(toHexString(storedSaltHash)) .append(toHexString(inputPasswordHash)) .toString() .getBytes()); return toHexString(finalHash).equalsIgnoreCase(storedPasswordHash); }
/** * Completes the Mac computation and resets the Mac for further use, maintaining the secret key * that the Mac was initialized with. * * @return the Mac result. */ byte[] doFinal() { if (first == true) { // compute digest for 1st pass; start with inner pad md.update(secret); md.update(pad1); } else { first = true; } try { // finish the inner digest byte[] tmp = md.digest(); // compute digest for 2nd pass; start with outer pad md.update(secret); md.update(pad2); // add result of 1st hash md.update(tmp); md.digest(tmp, 0, tmp.length); return tmp; } catch (DigestException e) { // should never occur throw new ProviderException(e); } }
public static FileDesc loadFile(Path root, Path file, int blocSize) throws NoSuchAlgorithmException, FileNotFoundException, IOException { MessageDigest md = MessageDigest.getInstance("SHA-512"); MessageDigest fileMd = MessageDigest.getInstance("SHA-512"); FileDesc desc = new FileDesc(file.toString(), null, null); List<Bloc> list = new ArrayList<Bloc>(); try (FileInputStream fis = new FileInputStream(root.resolve(file).toString())) { byte[] buf = new byte[blocSize]; byte[] h; int s; while ((s = fis.read(buf)) != -1) { int c; while (s < buf.length && (c = fis.read()) != -1) buf[s++] = (byte) c; fileMd.update(buf, 0, s); // padding byte p = 0; while (s < buf.length) buf[s++] = ++p; h = md.digest(buf); Bloc bloc = new Bloc(RollingChecksum.compute(buf), new Hash(h)); list.add(bloc); } h = fileMd.digest(); desc.fileHash = new Hash(h); desc.blocs = list.toArray(new Bloc[0]); } return desc; }
/** * 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()); } }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { String data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* read user input from console with readLine*/ BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(System.in); buffread = new BufferedReader(instrread); data = buffread.readLine(); } catch (IOException ioe) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if (buffread != null) { buffread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing buffread"); } finally { try { if (instrread != null) { instrread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing instrread"); } } } } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ SecureRandom r = new SecureRandom(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } }
public String modifyPassWord() throws Exception { UserbaseinfoDAO userDao = (UserbaseinfoDAO) DAOFactory.getIUserbaseinfoDAOInstance(); String useroldPassword = request.getParameter("myoldPassword"); String usernewPassword = request.getParameter("mynewPassword"); String userId = (String) ServletActionContext.getRequest().getSession().getAttribute("userId"); String DaoUserPass = userDao.getUserAllMsgById(Integer.parseInt(userId)).getUserPassword(); boolean Istrue = true; boolean Isrepeat = true; MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] md = md5.digest(useroldPassword.getBytes()); useroldPassword = new String(md); byte[] md1 = md5.digest(usernewPassword.getBytes()); usernewPassword = new String(md1); // 如果旧密码与数据库密码不匹配,提示用户错误消息 if (!DaoUserPass.equals(useroldPassword)) { Istrue = false; } else { // 比较新密码与原始密码是否一致,如果一致,提示用户新密码与旧密码不能一致 if (!DaoUserPass.equals(usernewPassword) && usernewPassword != "") { // 如果不一致,修改数据库中的密码 Isrepeat = false; // 没有重复 System.out.println("用户id=" + userId + "用户新密码=" + usernewPassword); DAOFactory.getIUserbaseinfoDAOInstance() .updatePassword(Integer.parseInt(userId), usernewPassword); } } System.out.println(Istrue + " " + Isrepeat); response.getWriter().print("[{\"isTrue\":" + Istrue + "},{\"isRepeat\":" + Isrepeat + "}]"); return null; }
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"); } }
public static byte[] publicKeyToAddress(String string) { byte[] publicKeyBytes = null; try { publicKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // System.out.println(Utils.toHex(publicKeyBytes)); // System.out.println(publicKeyBytes.length); byte[] out = new byte[20]; byte[] hash = new byte[256]; byte[] hash2 = new byte[256]; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(publicKeyBytes); hash2 = digest.digest(hash); RIPEMD160Digest digest160 = new RIPEMD160Digest(); digest160.update(hash, 0, hash.length); digest160.doFinal(out, 0); } catch (Exception e) { // TODO: handle exception } byte[] ripemd_bytes = null; byte[] checksum = new byte[4]; try { ripemd_bytes = org.apache.commons.codec.binary.Hex.decodeHex( ("00" + Utils.toHex(out).toUpperCase()).toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(ripemd_bytes); hash2 = digest.digest(hash); } catch (Exception e) { // TODO: handle exception } System.arraycopy(hash2, 0, checksum, 0, checksum.length); byte[] combined = new byte[1 + out.length + checksum.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < ripemd_bytes.length ? ripemd_bytes[i] : checksum[i - ripemd_bytes.length]; } // System.out.println(Utils.toHex(combined)); return (combined); }
/** * Generate MD5 signature * * @param session_key Key with which to sign data * @param length Length of signature * @param keylen Length of key * @param data Data to sign * @param datalength Length of data to sign * @return Signature for data * @throws CryptoException */ public byte[] sign(byte[] session_key, int length, int keylen, byte[] data, int datalength) throws CryptoException { byte[] shasig = new byte[20]; byte[] md5sig = new byte[16]; byte[] lenhdr = new byte[4]; byte[] signature = new byte[length]; this.setLittleEndian32(lenhdr, datalength); synchronized (digestLock) { sha1.reset(); sha1.update(session_key, 0, keylen); sha1.update(pad_54, 0, 40); sha1.update(lenhdr, 0, 4); sha1.update(data, 0, datalength); shasig = sha1.digest(); sha1.reset(); md5.reset(); md5.update(session_key, 0, keylen /* length */); md5.update(pad_92, 0, 48); md5.update(shasig, 0, 20); md5sig = md5.digest(); md5.reset(); System.arraycopy(md5sig, 0, signature, 0, length); } return signature; }
public static byte[] privateKeyToWif(String string, boolean testnet) { string = testnet ? "EF" + string : "80" + string; byte[] privateKeyBytes = new byte[string.length()]; byte[] checksum = new byte[4]; try { privateKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } byte[] hash = new byte[256]; byte[] hash2 = new byte[256]; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(privateKeyBytes); hash2 = digest.digest(hash); } catch (Exception e) { // TODO: handle exception } System.arraycopy(hash2, 0, checksum, 0, checksum.length); byte[] combined = new byte[privateKeyBytes.length + checksum.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < privateKeyBytes.length ? privateKeyBytes[i] : checksum[i - privateKeyBytes.length]; } return (combined); }
public void calculate_M1() { BigInteger N_Hash; BigInteger g_Hash; BigInteger I_Hash; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); // Calculate H(N) N_Hash = new BigInteger(md.digest(N.toString().getBytes())); md.reset(); // Calculate H(g) g_Hash = new BigInteger(md.digest(g.toString().getBytes())); md.reset(); // Calculate H(I) I_Hash = new BigInteger(md.digest(I.toString().getBytes())); md.reset(); // Calculate M1 M1 = new BigInteger( md.digest( (N_Hash.xor(g_Hash).toString() + I_Hash.toString() + s.toString() + A.toString() + B.toString() + K.toString()) .getBytes())); System.out.println("Client M1: " + M1.toString()); } catch (Exception e) { } }
// Validates HMAC-SHA1 signatures included in webhook notifications // to ensure notifications came from Square public static boolean isValidCallback(String callbackBody, String callbackSignature) { // Combine your webhook notification URL and the JSON body of the incoming request into a single // string String stringToSign = _webhookUrl + callbackBody; String result; // Generate the HMAC-SHA1 signature of the string, signed with your webhook signature key try { SecretKeySpec signingKey = new SecretKeySpec(_webhookSignatureKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(stringToSign.getBytes()); result = Base64.encodeBase64String(rawHmac); } catch (Exception e) { return false; } // Hash the two signatures a second time (to protect against timing attacks) and compare them try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); String hashedCallbackSignature = new String(digest.digest(callbackSignature.getBytes())); String hashedResult = new String(digest.digest(result.getBytes())); return hashedCallbackSignature.equals(hashedResult); } catch (NoSuchAlgorithmException e) { return false; } }
private static void xorProcess( byte[] data, int position, int length, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) { byte[] seed = new byte[32]; Curve25519.curve(seed, myPrivateKey, theirPublicKey); for (int i = 0; i < 32; i++) { seed[i] ^= nonce[i]; } MessageDigest sha256 = sha256(); seed = sha256.digest(seed); for (int i = 0; i < length / 32; i++) { byte[] key = sha256.digest(seed); for (int j = 0; j < 32; j++) { data[position++] ^= key[j]; seed[j] = (byte) (~seed[j]); } seed = sha256.digest(seed); } byte[] key = sha256.digest(seed); for (int i = 0; i < length % 32; i++) { data[position++] ^= key[i]; } }
/** * Computes a hash code based on the data that have been provided to this hasher. The result is * unspecified if this method is called more than once on the same instance. */ BytesHashCode hash() { checkNotDone(); done = true; return (bytes == digest.getDigestLength()) ? new BytesHashCode(digest.digest()) : new BytesHashCode(Arrays.copyOf(digest.digest(), bytes)); }
/** Write the signature file to the given output stream. */ private void generateSignatureFile(Manifest manifest, OutputStream out) throws IOException, GeneralSecurityException { out.write(("Signature-Version: 1.0\r\n").getBytes()); out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes()); // BASE64Encoder base64 = new BASE64Encoder(); MessageDigest md = MessageDigest.getInstance("SHA1"); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8"); // Digest of the entire manifest manifest.write(print); print.flush(); out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes()); Map<String, Attributes> entries = manifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { if (canceled) break; progressHelper.progress(ProgressEvent.PRORITY_NORMAL, "Generating signature file"); // Digest of the manifest stanza for this entry. String nameEntry = "Name: " + entry.getKey() + "\r\n"; print.print(nameEntry); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); out.write(nameEntry.getBytes()); out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes()); } }
/** * create from an issuer certificate and the serial number of the certificate it signed. * * @exception OCSPException if any problems occur creating the id fields. */ public CertificateID( String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull()); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert); digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new DEROctetString(digest.digest()); PublicKey issuerKey = issuerCert.getPublicKey(); ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest()); DERInteger serialNumber = new DERInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
private static byte[][] evpBytesTokey( int key_len, int iv_len, MessageDigest md, byte[] salt, byte[] data, int count) { byte[][] both = new byte[2][]; byte[] key = new byte[key_len]; int key_ix = 0; byte[] iv = new byte[iv_len]; int iv_ix = 0; both[0] = key; both[1] = iv; byte[] md_buf = null; int nkey = key_len; int niv = iv_len; int i = 0; if (data == null) { return both; } int addmd = 0; for (; ; ) { md.reset(); if (addmd++ > 0) { md.update(md_buf); } md.update(data); if (null != salt) { md.update(salt, 0, 8); } md_buf = md.digest(); for (i = 1; i < count; i++) { md.reset(); md.update(md_buf); md_buf = md.digest(); } i = 0; if (nkey > 0) { for (; ; ) { if (nkey == 0) break; if (i == md_buf.length) break; key[key_ix++] = md_buf[i]; nkey--; i++; } } if (niv > 0 && i != md_buf.length) { for (; ; ) { if (niv == 0) break; if (i == md_buf.length) break; iv[iv_ix++] = md_buf[i]; niv--; i++; } } if (nkey == 0 && niv == 0) { break; } } for (i = 0; i < md_buf.length; i++) { md_buf[i] = 0; } return both; }
boolean isManifestUpdated() { if (!mCacheFile.exists()) { Log.i("ManifestCheckerService", "updated: cache file does not exist"); return true; } try { MessageDigest dataDigester = MessageDigest.getInstance("MD5"); dataDigester.update(mFetcher.getData(), 0, mFetcher.getDataLen()); byte[] dataDigest = dataDigester.digest(); MessageDigest fileDigester = MessageDigest.getInstance("MD5"); FileInputStream is = new FileInputStream(mCacheFile); byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { fileDigester.update(buf, 0, len); } is.close(); byte[] fileDigest = fileDigester.digest(); if (Arrays.equals(dataDigest, fileDigest)) { return false; } Log.i("ManifestCheckerService", "updated: digests differ"); } catch (Exception e) { Log.e("ManifestFetcher", "caught exception: " + e.getMessage()); e.printStackTrace(); } return true; }