本文整理匯總了Java中java.security.MessageDigest.isEqual方法的典型用法代碼示例。如果您正苦於以下問題:Java MessageDigest.isEqual方法的具體用法?Java MessageDigest.isEqual怎麽用?Java MessageDigest.isEqual使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.security.MessageDigest
的用法示例。
在下文中一共展示了MessageDigest.isEqual方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: equals
import java.security.MessageDigest; //導入方法依賴的package包/類
/**
* Returns {@code true} if the {@code tokenCredentials} argument is logically equal to the
* {@code accountCredentials} argument.
* <p/>
* <p>If both arguments are either a byte array (byte[]), char array (char[]) or String, they will be both be
* converted to raw byte arrays via the {@link #toBytes toBytes} method first, and then resulting byte arrays
* are compared via {@link Arrays#equals(byte[], byte[]) Arrays.equals(byte[],byte[])}.</p>
* <p/>
* <p>If either argument cannot be converted to a byte array as described, a simple Object <code>equals</code>
* comparison is made.</p>
* <p/>
* <p>Subclasses should override this method for more explicit equality checks.
*
* @param tokenCredentials the {@code AuthenticationToken}'s associated credentials.
* @param accountCredentials the {@code AuthenticationInfo}'s stored credentials.
* @return {@code true} if the {@code tokenCredentials} are equal to the {@code accountCredentials}.
*/
protected boolean equals(Object tokenCredentials, Object accountCredentials) {
if (tokenCredentials == null || accountCredentials == null) {
return false;
}
if (log.isDebugEnabled()) {
log.debug("Performing credentials equality check for tokenCredentials of type [" +
tokenCredentials.getClass().getName() + " and accountCredentials of type [" +
accountCredentials.getClass().getName() + "]");
}
if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
if (log.isDebugEnabled()) {
log.debug("Both credentials arguments can be easily converted to byte arrays. Performing " +
"array equals comparison");
}
byte[] tokenBytes = toBytes(tokenCredentials);
byte[] accountBytes = toBytes(accountCredentials);
return MessageDigest.isEqual(tokenBytes, accountBytes);
} else {
return accountCredentials.equals(tokenCredentials);
}
}
示例2: equals
import java.security.MessageDigest; //導入方法依賴的package包/類
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SecretKey))
return false;
String thatAlg = ((SecretKey)obj).getAlgorithm();
if (!(thatAlg.equalsIgnoreCase("DES")))
return false;
byte[] thatKey = ((SecretKey)obj).getEncoded();
boolean ret = MessageDigest.isEqual(this.key, thatKey);
java.util.Arrays.fill(thatKey, (byte)0x00);
return ret;
}
示例3: equals
import java.security.MessageDigest; //導入方法依賴的package包/類
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SecretKey))
return false;
String thatAlg = ((SecretKey)obj).getAlgorithm();
if (!(thatAlg.equalsIgnoreCase("DESede"))
&& !(thatAlg.equalsIgnoreCase("TripleDES")))
return false;
byte[] thatKey = ((SecretKey)obj).getEncoded();
boolean ret = MessageDigest.isEqual(this.key, thatKey);
java.util.Arrays.fill(thatKey, (byte)0x00);
return ret;
}
示例4: verifySign
import java.security.MessageDigest; //導入方法依賴的package包/類
/**
* Verifies the validity of checksum field
*
* @param data the application data
* @param offset the offset where the data begins
* @param len the length of the application data
*
* @throws GSSException if an error occurs in the checksum calculation
*/
public final boolean verifySign(byte[] data, int offset, int len)
throws GSSException {
// debug("\t====In verifySign:====\n");
// debug("\t\t checksum: [" + getHexBytes(checksum) + "]\n");
// debug("\t\t data = [" + getHexBytes(data) + "]\n");
byte[] myChecksum = getChecksum(data, offset, len);
// debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");
if (MessageDigest.isEqual(checksum, myChecksum)) {
// debug("\t\t====Checksum PASS:====\n");
return true;
}
return false;
}
示例5: equals
import java.security.MessageDigest; //導入方法依賴的package包/類
/**
* Tests for equality between the specified object and this
* object. Two SecretKeySpec objects are considered equal if
* they are both SecretKey instances which have the
* same case-insensitive algorithm name and key encoding.
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* <code>obj</code> is null or otherwise.
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SecretKey))
return false;
String thatAlg = ((SecretKey)obj).getAlgorithm();
if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
if ((!(thatAlg.equalsIgnoreCase("DESede"))
|| !(this.algorithm.equalsIgnoreCase("TripleDES")))
&& (!(thatAlg.equalsIgnoreCase("TripleDES"))
|| !(this.algorithm.equalsIgnoreCase("DESede"))))
return false;
}
byte[] thatKey = ((SecretKey)obj).getEncoded();
return MessageDigest.isEqual(this.key, thatKey);
}
示例6: equals
import java.security.MessageDigest; //導入方法依賴的package包/類
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof SecretKey))
return false;
SecretKey that = (SecretKey) obj;
if (!(that.getAlgorithm().equalsIgnoreCase(getAlgorithm())))
return false;
if (!(that.getFormat().equalsIgnoreCase("RAW")))
return false;
byte[] thatEncoded = that.getEncoded();
boolean ret = MessageDigest.isEqual(key, that.getEncoded());
java.util.Arrays.fill(thatEncoded, (byte)0x00);
return ret;
}
示例7: open
import java.security.MessageDigest; //導入方法依賴的package包/類
/**
* Decrypt a ciphertext using the given key and nonce.
*
* @param nonce a 24-byte nonce
* @param ciphertext the encrypted message
* @return an {@link Optional} of the original plaintext, or if either the key, nonce, or
* ciphertext was modified, an empty {@link Optional}
* @see #nonce(ByteString)
* @see #nonce()
*/
public Optional<ByteString> open(@Nonnull ByteString nonce, @Nonnull ByteString ciphertext) {
final byte[] in = ciphertext.toByteArray();
final XSalsa20Engine xsalsa20 = new XSalsa20Engine();
final Poly1305 poly1305 = new Poly1305();
// initialize XSalsa20
xsalsa20.init(false, new ParametersWithIV(new KeyParameter(key), nonce.toByteArray()));
// generate mac subkey
final byte[] sk = new byte[32];
xsalsa20.processBytes(sk, 0, sk.length, sk, 0);
// hash ciphertext
poly1305.init(new KeyParameter(sk));
final int len = Math.max(ciphertext.size() - 16, 0);
poly1305.update(in, 16, len);
final byte[] calculatedMAC = new byte[16];
poly1305.doFinal(calculatedMAC, 0);
// extract mac
final byte[] presentedMAC = new byte[16];
System.arraycopy(in, 0, presentedMAC, 0, Math.min(ciphertext.size(), 16));
// compare macs
if (!MessageDigest.isEqual(calculatedMAC, presentedMAC)) {
return Optional.empty();
}
// decrypt ciphertext
final byte[] plaintext = new byte[len];
xsalsa20.processBytes(in, 16, plaintext.length, plaintext, 0);
return Optional.of(ByteString.of(plaintext));
}
示例8: restoreWithTimestamp
import java.security.MessageDigest; //導入方法依賴的package包/類
<T> TimestampedState<T> restoreWithTimestamp(final Cookie cookie, final Class<T> type) {
final String value = cookie.getValue();
final String[] parts = value.split("\\|", 5);
final byte[] atime = DECODER.decode(parts[1]);
final long atimeLong = atime(atime);
if (atimeLong + timeout < timeSource.getAsLong()) {
throw new IllegalArgumentException("Given value has timed out at: " + Instant.ofEpochSecond(atimeLong));
}
final byte[] tid = DECODER.decode(parts[2]);
if (!MessageDigest.isEqual(tid, edition.tid)) {
throw new IllegalArgumentException(String.format("Given TID `%s`, mismatches current TID `%s`",
new BigInteger(tid).toString(16), new BigInteger(edition.tid).toString(16)));
}
final KeySource keySource = edition.keySource();
final int lastSeparatorIdx = value.lastIndexOf('|');
final byte[] mac = DECODER.decode(parts[4]);
final byte[] calculated = mac(edition.authenticationAlgorithm, value.substring(0, lastSeparatorIdx),
keySource.authenticationKey());
if (!MessageDigest.isEqual(mac, calculated)) {
throw new IllegalArgumentException("Cookie value fails authenticity check");
}
final byte[] iv = DECODER.decode(parts[3]);
final byte[] encrypted = DECODER.decode(parts[0]);
final byte[] clear = decrypt(edition.encryptionAlgorithm, iv, encrypted, keySource.encryptionKey());
@SuppressWarnings("unchecked")
final T ret = (T) deserialization.apply(type, clear);
return new TimestampedState<>(ret, atimeLong);
}
示例9: verifyMac
import java.security.MessageDigest; //導入方法依賴的package包/類
private void verifyMac(File file, Mac mac, Optional<byte[]> theirDigest)
throws FileNotFoundException, InvalidMacException
{
try {
MessageDigest digest = MessageDigest.getInstance("SHA256");
FileInputStream fin = new FileInputStream(file);
int remainingData = Util.toIntExact(file.length()) - mac.getMacLength();
byte[] buffer = new byte[4096];
while (remainingData > 0) {
int read = fin.read(buffer, 0, Math.min(buffer.length, remainingData));
mac.update(buffer, 0, read);
digest.update(buffer, 0, read);
remainingData -= read;
}
byte[] ourMac = mac.doFinal();
byte[] theirMac = new byte[mac.getMacLength()];
Util.readFully(fin, theirMac);
if (!MessageDigest.isEqual(ourMac, theirMac)) {
throw new InvalidMacException("MAC doesn't match!");
}
byte[] ourDigest = digest.digest(theirMac);
if (theirDigest.isPresent() && !MessageDigest.isEqual(ourDigest, theirDigest.get())) {
throw new InvalidMacException("Digest doesn't match!");
}
} catch (IOException | ArithmeticException e1) {
throw new InvalidMacException(e1);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
示例10: verify
import java.security.MessageDigest; //導入方法依賴的package包/類
boolean verify(Key key, SignedInfo si, byte[] sig,
XMLValidateContext context)
throws InvalidKeyException, SignatureException, XMLSignatureException
{
if (key == null || si == null || sig == null) {
throw new NullPointerException();
}
if (!(key instanceof SecretKey)) {
throw new InvalidKeyException("key must be SecretKey");
}
if (hmac == null) {
try {
hmac = Mac.getInstance(getJCAAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
}
if (outputLengthSet && outputLength < getDigestLength()) {
throw new XMLSignatureException
("HMACOutputLength must not be less than " + getDigestLength());
}
hmac.init((SecretKey)key);
((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
byte[] result = hmac.doFinal();
return MessageDigest.isEqual(sig, result);
}
示例11: getDownloadStatus
import java.security.MessageDigest; //導入方法依賴的package包/類
private DownloadStatus getDownloadStatus(String uri, byte[] theirDigest) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_SUCCESSFUL);
long pendingDownloadId = TextSecurePreferences.getUpdateApkDownloadId(context);
byte[] pendingDigest = getPendingDigest(context);
Cursor cursor = downloadManager.query(query);
try {
DownloadStatus status = new DownloadStatus(DownloadStatus.Status.MISSING, -1);
while (cursor != null && cursor.moveToNext()) {
int jobStatus = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
String jobRemoteUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_URI));
long downloadId = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID));
byte[] digest = getDigestForDownloadId(downloadId);
if (jobRemoteUri != null && jobRemoteUri.equals(uri) && downloadId == pendingDownloadId) {
if (jobStatus == DownloadManager.STATUS_SUCCESSFUL &&
digest != null && pendingDigest != null &&
MessageDigest.isEqual(pendingDigest, theirDigest) &&
MessageDigest.isEqual(digest, theirDigest))
{
return new DownloadStatus(DownloadStatus.Status.COMPLETE, downloadId);
} else if (jobStatus != DownloadManager.STATUS_SUCCESSFUL) {
status = new DownloadStatus(DownloadStatus.Status.PENDING, downloadId);
}
}
}
return status;
} finally {
if (cursor != null) cursor.close();
}
}
示例12: run
import java.security.MessageDigest; //導入方法依賴的package包/類
private void run() throws Exception {
byte[] data = new byte[6706];
MessageDigest md = null;
// Initialize input data
RandomFactory.getRandom().nextBytes(data);
String[] algorithmArr = { "SHA", "Sha", "MD5", "md5", "SHA-224",
"SHA-256", "SHA-384", "SHA-512", "SHA3-224", "SHA3-256",
"SHA3-384", "SHA3-512" };
for (String algorithm : algorithmArr) {
try {
md = MessageDigest.getInstance(algorithm);
for (UpdateDigestMethod updateMethod : UpdateDigestMethod
.values()) {
byte[] output = updateMethod.updateDigest(data, md);
// Get the output and the "correct" one
byte[] standard = md.digest(data);
// Compare input and output
if (!MessageDigest.isEqual(output, standard)) {
throw new RuntimeException(
"Test failed at algorithm/provider/numUpdate:"
+ algorithm + "/" + md.getProvider()
+ "/" + updateMethod);
}
}
} catch (NoSuchAlgorithmException nae) {
if (algorithm.startsWith("SHA3") && !isSHA3supported()) {
continue;
} else {
throw nae;
}
}
}
out.println("All "
+ algorithmArr.length * UpdateDigestMethod.values().length
+ " tests Passed");
}
示例13: verifyManifestMainAttrs
import java.security.MessageDigest; //導入方法依賴的package包/類
private boolean verifyManifestMainAttrs(Manifest sf,
ManifestDigester md)
throws IOException, SignatureException
{
Attributes mattr = sf.getMainAttributes();
boolean attrsVerified = true;
// go through all the attributes and process
// digest entries for the manifest main attributes
for (Map.Entry<Object,Object> se : mattr.entrySet()) {
String key = se.getKey().toString();
if (key.toUpperCase(Locale.ENGLISH).endsWith(ATTR_DIGEST)) {
String algorithm =
key.substring(0, key.length() - ATTR_DIGEST.length());
MessageDigest digest = getDigest(algorithm);
if (digest != null) {
ManifestDigester.Entry mde =
md.get(ManifestDigester.MF_MAIN_ATTRS, false);
byte[] computedHash = mde.digest(digest);
byte[] expectedHash =
Base64.getMimeDecoder().decode((String)se.getValue());
if (debug != null) {
debug.println("Signature File: " +
"Manifest Main Attributes digest " +
digest.getAlgorithm());
debug.println( " sigfile " + toHex(expectedHash));
debug.println( " computed " + toHex(computedHash));
debug.println();
}
if (MessageDigest.isEqual(computedHash,
expectedHash)) {
// good
} else {
// we will *not* continue and verify each section
attrsVerified = false;
if (debug != null) {
debug.println("Verification of " +
"Manifest main attributes failed");
debug.println();
}
break;
}
}
}
}
// this method returns 'true' if either:
// . manifest main attributes were not signed, or
// . manifest main attributes were signed and verified
return attrsVerified;
}
示例14: engineLoad
import java.security.MessageDigest; //導入方法依賴的package包/類
public void engineLoad(InputStream in, char[] passwd)
throws IOException, NoSuchAlgorithmException, CertificateException
{
MessageDigest md = MessageDigest.getInstance("SHA");
if (passwd != null) md.update(charsToBytes(passwd));
md.update("Mighty Aphrodite".getBytes("UTF-8")); // HAR HAR
aliases.clear();
trustedCerts.clear();
privateKeys.clear();
certChains.clear();
dates.clear();
if (in == null) return;
DataInputStream din = new DataInputStream(new DigestInputStream(in, md));
if (din.readInt() != MAGIC)
throw new IOException("not a JavaKeyStore");
din.readInt(); // version no.
final int n = din.readInt();
aliases.ensureCapacity(n);
if (n < 0)
throw new LoadKeystoreException("Malformed key store");
for (int i = 0; i < n; i++)
{
int type = din.readInt();
String alias = din.readUTF();
aliases.add(alias);
dates.put(alias, new Date(din.readLong()));
switch (type)
{
case PRIVATE_KEY:
int len = din.readInt();
byte[] encoded = new byte[len];
din.read(encoded);
privateKeys.put(alias, encoded);
int count = din.readInt();
Certificate[] chain = new Certificate[count];
for (int j = 0; j < count; j++)
chain[j] = readCert(din);
certChains.put(alias, chain);
break;
case TRUSTED_CERT:
trustedCerts.put(alias, readCert(din));
break;
default:
throw new LoadKeystoreException("Malformed key store");
}
}
if (passwd != null) {
byte[] computedHash = md.digest();
byte[] storedHash = new byte[20];
din.read(storedHash);
if (!MessageDigest.isEqual(storedHash, computedHash)) {
throw new LoadKeystoreException("Incorrect password, or integrity check failed.");
}
}
}
示例15: deriveKey
import java.security.MessageDigest; //導入方法依賴的package包/類
private static byte[] deriveKey(final Mac prf, final byte[] password,
byte[] salt, int iterCount, int keyLengthInBit) {
int keyLength = keyLengthInBit/8;
byte[] key = new byte[keyLength];
try {
int hlen = prf.getMacLength();
int intL = (keyLength + hlen - 1)/hlen; // ceiling
int intR = keyLength - (intL - 1)*hlen; // residue
byte[] ui = new byte[hlen];
byte[] ti = new byte[hlen];
// SecretKeySpec cannot be used, since password can be empty here.
SecretKey macKey = new SecretKey() {
private static final long serialVersionUID = 7874493593505141603L;
@Override
public String getAlgorithm() {
return prf.getAlgorithm();
}
@Override
public String getFormat() {
return "RAW";
}
@Override
public byte[] getEncoded() {
return password;
}
@Override
public int hashCode() {
return Arrays.hashCode(password) * 41 +
prf.getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (this.getClass() != obj.getClass()) return false;
SecretKey sk = (SecretKey)obj;
return prf.getAlgorithm().equalsIgnoreCase(
sk.getAlgorithm()) &&
MessageDigest.isEqual(password, sk.getEncoded());
}
};
prf.init(macKey);
byte[] ibytes = new byte[4];
for (int i = 1; i <= intL; i++) {
prf.update(salt);
ibytes[3] = (byte) i;
ibytes[2] = (byte) ((i >> 8) & 0xff);
ibytes[1] = (byte) ((i >> 16) & 0xff);
ibytes[0] = (byte) ((i >> 24) & 0xff);
prf.update(ibytes);
prf.doFinal(ui, 0);
System.arraycopy(ui, 0, ti, 0, ui.length);
for (int j = 2; j <= iterCount; j++) {
prf.update(ui);
prf.doFinal(ui, 0);
// XOR the intermediate Ui's together.
for (int k = 0; k < ui.length; k++) {
ti[k] ^= ui[k];
}
}
if (i == intL) {
System.arraycopy(ti, 0, key, (i-1)*hlen, intR);
} else {
System.arraycopy(ti, 0, key, (i-1)*hlen, hlen);
}
}
} catch (GeneralSecurityException gse) {
throw new RuntimeException("Error deriving PBKDF2 keys");
}
return key;
}