use of java.security.DigestInputStream in project AndroidUtilLib by SiberiaDante.
the class SDMD5Util method hashEncodeFile2Byte.
/**
* MD5加密文件
*
* @param file 文件
* @return 文件的MD5校验码
*/
public static byte[] hashEncodeFile2Byte(final File file) {
if (file == null)
return null;
FileInputStream fis = null;
DigestInputStream digestInputStream;
try {
fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
digestInputStream = new DigestInputStream(fis, md);
byte[] buffer = new byte[256 * 1024];
while (true) {
if (!(digestInputStream.read(buffer) > 0))
break;
}
md = digestInputStream.getMessageDigest();
return md.digest();
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
return null;
} finally {
SDCloseUtil.closeIO(fis);
}
}
use of java.security.DigestInputStream in project felix by apache.
the class OSGiRepositoryImpl method getSHA256.
static // TODO find a good place for this
String getSHA256(// TODO find a good place for this
String uri) throws // TODO find a good place for this
IOException, // TODO find a good place for this
NoSuchAlgorithmException {
InputStream is = new URL(uri).openStream();
MessageDigest md = MessageDigest.getInstance("SHA-256");
// Use a digest inputstream as using byte arrays directly to compute the SHA-256 can
// have big effects on memory consumption. I.e. you don't want to have to read the
// entire resource in memory. We rather stream it through...
DigestInputStream dis = new DigestInputStream(is, md);
byte[] buffer = new byte[16384];
while (dis.read(buffer) != -1) {
// we just drain the stream here to compute the Message Digest
}
// SHA-256 is always 64 hex characters
StringBuilder sb = new StringBuilder(64);
for (byte b : md.digest()) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
use of java.security.DigestInputStream in project ranger by apache.
the class RangerKeyStore method engineLoad.
@Override
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
synchronized (keyEntries) {
List<XXRangerKeyStore> rangerKeyDetails = dbOperationLoad();
DataInputStream dis;
MessageDigest md = null;
if (rangerKeyDetails == null || rangerKeyDetails.size() < 1) {
return;
}
keyEntries.clear();
if (password != null) {
md = getKeyedMessageDigest(password);
}
byte[] computed = {};
if (md != null) {
computed = md.digest();
}
for (XXRangerKeyStore rangerKey : rangerKeyDetails) {
String encoded = rangerKey.getEncoded();
byte[] data = DatatypeConverter.parseBase64Binary(encoded);
if (data != null && data.length > 0) {
stream = new ByteArrayInputStream(data);
} else {
logger.error("No Key found for alias " + rangerKey.getAlias());
}
if (computed != null) {
int counter = 0;
for (int i = computed.length - 1; i >= 0; i--) {
if (computed[i] != data[data.length - (1 + counter)]) {
Throwable t = new UnrecoverableKeyException("Password verification failed");
throw (IOException) new IOException("Keystore was tampered with, or " + "password was incorrect").initCause(t);
} else {
counter++;
}
}
}
if (password != null) {
dis = new DataInputStream(new DigestInputStream(stream, md));
} else {
dis = new DataInputStream(stream);
}
ObjectInputStream ois = null;
try {
String alias;
SecretKeyEntry entry = new SecretKeyEntry();
// read the alias
alias = rangerKey.getAlias();
// read the (entry creation) date
entry.date = new Date(rangerKey.getCreatedDate());
entry.cipher_field = rangerKey.getCipher();
entry.bit_length = rangerKey.getBitLength();
entry.description = rangerKey.getDescription();
entry.version = rangerKey.getVersion();
entry.attributes = rangerKey.getAttributes();
// read the sealed key
try {
ois = new ObjectInputStream(dis);
entry.sealedKey = (SealedObject) ois.readObject();
} catch (ClassNotFoundException cnfe) {
throw new IOException(cnfe.getMessage());
}
// Add the entry to the list
keyEntries.put(alias, entry);
} finally {
if (ois != null) {
ois.close();
} else {
dis.close();
}
}
}
}
}
use of java.security.DigestInputStream in project jdk8u_jdk by JetBrains.
the class JceKeyStore method engineLoad.
/**
* Loads the keystore from the given input stream.
*
* <p>If a password is given, it is used to check the integrity of the
* keystore data. Otherwise, the integrity of the keystore is not checked.
*
* @param stream the input stream from which the keystore is loaded
* @param password the (optional) password used to check the integrity of
* the keystore.
*
* @exception IOException if there is an I/O or format problem with the
* keystore data
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
synchronized (entries) {
DataInputStream dis;
MessageDigest md = null;
CertificateFactory cf = null;
Hashtable<String, CertificateFactory> cfs = null;
ByteArrayInputStream bais = null;
byte[] encoded = null;
if (stream == null)
return;
if (password != null) {
md = getPreKeyedHash(password);
dis = new DataInputStream(new DigestInputStream(stream, md));
} else {
dis = new DataInputStream(stream);
}
// NOTE: don't pass dis to ois at this point or it'll fail to load
// the keystore!!!
ObjectInputStream ois = null;
try {
// Body format: see store method
int xMagic = dis.readInt();
int xVersion = dis.readInt();
// versions 1 and 2
if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
throw new IOException("Invalid keystore format");
}
if (xVersion == VERSION_1) {
cf = CertificateFactory.getInstance("X509");
} else {
// version 2
cfs = new Hashtable<String, CertificateFactory>(3);
}
entries.clear();
int count = dis.readInt();
for (int i = 0; i < count; i++) {
int tag;
String alias;
tag = dis.readInt();
if (tag == 1) {
// private-key entry
PrivateKeyEntry entry = new PrivateKeyEntry();
// read the alias
alias = dis.readUTF();
// read the (entry creation) date
entry.date = new Date(dis.readLong());
// read the private key
try {
entry.protectedKey = new byte[dis.readInt()];
} catch (OutOfMemoryError e) {
throw new IOException("Keysize too big");
}
dis.readFully(entry.protectedKey);
// read the certificate chain
int numOfCerts = dis.readInt();
try {
if (numOfCerts > 0) {
entry.chain = new Certificate[numOfCerts];
}
} catch (OutOfMemoryError e) {
throw new IOException("Too many certificates in " + "chain");
}
for (int j = 0; j < numOfCerts; j++) {
if (xVersion == 2) {
// read the certificate type, and instantiate a
// certificate factory of that type (reuse
// existing factory if possible)
String certType = dis.readUTF();
if (cfs.containsKey(certType)) {
// reuse certificate factory
cf = cfs.get(certType);
} else {
// create new certificate factory
cf = CertificateFactory.getInstance(certType);
// store the certificate factory so we can
// reuse it later
cfs.put(certType, cf);
}
}
// instantiate the certificate
try {
encoded = new byte[dis.readInt()];
} catch (OutOfMemoryError e) {
throw new IOException("Certificate too big");
}
dis.readFully(encoded);
bais = new ByteArrayInputStream(encoded);
entry.chain[j] = cf.generateCertificate(bais);
}
// Add the entry to the list
entries.put(alias, entry);
} else if (tag == 2) {
// trusted certificate entry
TrustedCertEntry entry = new TrustedCertEntry();
// read the alias
alias = dis.readUTF();
// read the (entry creation) date
entry.date = new Date(dis.readLong());
// read the trusted certificate
if (xVersion == 2) {
// read the certificate type, and instantiate a
// certificate factory of that type (reuse
// existing factory if possible)
String certType = dis.readUTF();
if (cfs.containsKey(certType)) {
// reuse certificate factory
cf = cfs.get(certType);
} else {
// create new certificate factory
cf = CertificateFactory.getInstance(certType);
// store the certificate factory so we can
// reuse it later
cfs.put(certType, cf);
}
}
try {
encoded = new byte[dis.readInt()];
} catch (OutOfMemoryError e) {
throw new IOException("Certificate too big");
}
dis.readFully(encoded);
bais = new ByteArrayInputStream(encoded);
entry.cert = cf.generateCertificate(bais);
// Add the entry to the list
entries.put(alias, entry);
} else if (tag == 3) {
// secret-key entry
SecretKeyEntry entry = new SecretKeyEntry();
// read the alias
alias = dis.readUTF();
// read the (entry creation) date
entry.date = new Date(dis.readLong());
// read the sealed key
try {
ois = new ObjectInputStream(dis);
entry.sealedKey = (SealedObject) ois.readObject();
// NOTE: don't close ois here since we are still
// using dis!!!
} catch (ClassNotFoundException cnfe) {
throw new IOException(cnfe.getMessage());
}
// Add the entry to the list
entries.put(alias, entry);
} else {
throw new IOException("Unrecognized keystore entry");
}
}
/*
* If a password has been provided, we check the keyed digest
* at the end. If this check fails, the store has been tampered
* with
*/
if (password != null) {
byte[] computed, actual;
computed = md.digest();
actual = new byte[computed.length];
dis.readFully(actual);
for (int i = 0; i < computed.length; i++) {
if (computed[i] != actual[i]) {
throw new IOException("Keystore was tampered with, or " + "password was incorrect", new UnrecoverableKeyException("Password verification failed"));
}
}
}
} finally {
if (ois != null) {
ois.close();
} else {
dis.close();
}
}
}
}
use of java.security.DigestInputStream in project bnd by bndtools.
the class NexusOBR method put.
@Override
public synchronized PutResult put(InputStream stream, PutOptions options) throws Exception {
/* determine if the put is allowed */
if (readOnly) {
throw new IOException("Repository is read-only");
}
if (options == null)
options = DEFAULTOPTIONS;
/* both parameters are required */
if (stream == null)
throw new IllegalArgumentException("No stream and/or options specified");
/*
* setup a new stream that encapsulates the stream and calculates (when
* needed) the digest
*/
DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("SHA-1"));
File tmpFile = null;
try {
/*
* copy the artifact from the (new/digest) stream into a temporary
* file in the root directory of the repository
*/
tmpFile = IO.createTempFile(null, "put", ".bnd");
IO.copy(dis, tmpFile);
/* beforeGet the digest if available */
byte[] disDigest = dis.getMessageDigest().digest();
if (options.digest != null && !Arrays.equals(options.digest, disDigest))
throw new IOException("Retrieved artifact digest doesn't match specified digest");
/* put the artifact into the repository (from the temporary file) */
URL url = putArtifact(tmpFile);
PutResult result = new PutResult();
if (url != null) {
result.digest = disDigest;
result.artifact = url.toURI();
}
return result;
} finally {
if (tmpFile != null && tmpFile.exists()) {
IO.delete(tmpFile);
}
}
}
Aggregations