List of usage examples for java.security MessageDigest reset
public void reset()
From source file:it.polito.ai.polibox.client.http.action.AbstractFileAction.java
/** * upload/*from www .j a v a 2 s . c o m*/ */ public void upload(Resource r) { FileMapInterface f = fileMapLoader.load(); if (r.isDirectory()) { createDirectoryHttp(r); f.changeElementToList(getTargetList(), r); return; } else if (!r.isDirectory()) { createFileHttp(r); f.changeElementToList(getTargetList(), r); // continua con upload // System.out.println("id:"+r.getId()+"|version:"+r.getVersion()+"|"); File file; FileInputStream fis = null; try { file = new File(r.getName()); fis = new FileInputStream(file); byte[] buffer = new byte[FilesystemTools.CHUNK_SIZE]; int bytesRead; int index, i; String s, d; WebTarget target = helper.getWebTarget().path("rest/file/" + r.getId() + "/" + r.getVersion()); Form form; index = 0; byte[] b2, bite; MessageDigest md = MessageDigest.getInstance("SHA3-512"); while ((bytesRead = fis.read(buffer)) != -1) { if (bytesRead < buffer.length) { b2 = new byte[bytesRead]; for (i = 0; i < b2.length; i++) { b2[i] = buffer[i]; } buffer = b2; } if (index == r.getChunkNumber()) { /** * questo mi serve per i file molto grossi. il so mi splitta il file in versioni differenti, * nel server c' il merge quindi non troppi problemi arrivano. */ createFileHttp(r); f.changeElementToList(getTargetList(), r); } s = Base64.encodeBase64String(buffer); // System.out.println("ho letto:"+bytesRead+" bytes |"+buffer.length+"|"+md+"|"); md.reset(); md.update(s.getBytes("UTF-8"));//calcolo digest bite = md.digest(); d = org.bouncycastle.util.encoders.Hex.toHexString(bite); // System.out.println("digest:"+d); form = new Form(); form.param("version", "" + r.getVersion()); form.param("resource", "" + r.getId()); form.param("chunkNumber", "" + index); form.param("digest", d); form.param("data", s); // System.out.println("version:"+r.getVersion()+"|resource:"+r.getId()+"|chunk:"+index+"|of:"+r.getChunkNumber()+"|"); target.request(MediaType.APPLICATION_JSON_TYPE).headers(helper.getHeaders()).post( Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), new GenericType<Response<Resource>>() { }); index++; } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } finally { if (fis != null) { try { fis.close(); fis = null; } catch (IOException e) { throw new RuntimeException(e); } } } } }
From source file:org.wso2.carbon.security.util.ServerCrypto.java
@Override /**// w w w .j a v a2s. c om * @see org.apache.ws.security.components.crypto.Crypto#getAliasForX509CertThumb(byte[]) */ public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException { Certificate cert; MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { throw new WSSecurityException(0, "noSHA1availabe"); } try { for (Enumeration e = keystore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = this.getCertificates(alias); if (certs == null || certs.length == 0) { return null; } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError"); } byte[] data = sha.digest(); if (Arrays.equals(data, thumb)) { return alias; } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore"); } return null; }
From source file:de.bluepair.sci.client.SHAUtils.java
public static <T> Map<String, String> sha512(Path path, Predicate<T> gard, T testValue, long blockSizePref, boolean forceBlockSize) { if (Files.notExists(path)) { return null; }//from w ww . jav a 2 s. com MessageDigest md = getDigest(); MessageDigest md1 = getDigest(); if (!gard.test(testValue)) { return null; } long blockSize = blockSizePref; long size = -1; try { size = Files.size(path); if (!forceBlockSize) {// maximal 10 hashsummen // sonst hab ich zu viele in der datei // stehen! while (size / blockSize > 10) { blockSize += blockSizePref; } } } catch (IOException e) { blockSize = blockSizePref; return null; } Map<String, String> map = new HashMap<>(); long lastStart = 0; long stepDown = blockSize; try (final SeekableByteChannel fileChannel = Files.newByteChannel(path, StandardOpenOption.READ);) { final ByteBuffer buffer = ByteBuffer.allocateDirect(8192); int last; do { if (!gard.test(testValue) || Files.notExists(path)) { return null; } buffer.clear(); last = fileChannel.read(buffer); buffer.flip(); md.update(buffer); // calc 2checksups buffer.flip(); md1.update(buffer); if (last > 0) { stepDown -= last; } // wenn ich ein 100mb netzwerk habe // ~ca. 5MB bertragung // also bei abbruch kann wiederaufgesetzt werden wenn die summen // bekannt sind. // ~hnlich Blcke berechen also // 0-5 c1 // 0-10 c2 // 5-10 c3 ... if (stepDown <= 0 || (last <= 0)) { long len = (blockSize + Math.abs(stepDown)); if (stepDown > 0) { // kottektur wenn last <0 len = blockSize - stepDown; } stepDown = blockSize; map.put("sha512_" + lastStart + "_" + len, Hex.encodeHexString(md1.digest())); lastStart += len; md1.reset(); } } while (last > 0); } catch (IOException ex) { Logger.getLogger(FileAnalysis.class.getName()).log(Level.SEVERE, null, ex); return null; } final byte[] sha1hash = md.digest(); map.put("sha512", Hex.encodeHexString(sha1hash)); return map; }
From source file:com.google.acre.script.HostEnv.java
@JSFunction public String hash(String algorithm, String str, boolean to_hex) { try {/* w w w .ja v a2 s.co m*/ MessageDigest alg = MessageDigest.getInstance(algorithm); alg.reset(); alg.update(str.getBytes()); byte digest[] = alg.digest(); if (to_hex) { return new String(Hex.encodeHex(digest)); } else { return new String(Base64.encodeBase64(digest)); } } catch (NoSuchAlgorithmException e) { throw new JSConvertableException("Unable to load algoritm: " + algorithm).newJSException(this); } }
From source file:inti.ws.spring.resource.template.TemplateResource.java
@Override public void update() throws Exception { ExpressionFactory factory;/*from w w w .jav a 2 s . c o m*/ ValueExpression var; Object val; StringBuilder builder = new StringBuilder(2048); MessageDigest digest = DIGESTS.get(); factory = ExpressionFactory.newInstance(); for (WebResource file : files) { if (file.hasChanged()) { file.update(); } builder.append(applyTemplate(factory, file.getName(), file.getContent().replaceAll("\\s+", " "))); builder.append(','); } builder.delete(builder.length() - 1, builder.length()); super.update(); content = factory.createValueExpression(context, compressedFile, String.class); var = factory.createValueExpression(context, "${files}", String.class); var.setValue(context, builder.toString()); if (parameters != null) { for (Map.Entry<String, Object> parameter : parameters.entrySet()) { var = factory.createValueExpression(context, "${" + parameter.getKey() + '}', String.class); val = parameter.getValue(); if ("$filename".equals(val)) { val = resource.getFile(); } else if ("$modulename".equals(val)) { val = moduleName; } var.setValue(context, val); } } compressedFile = (String) content.getValue(context); builder.delete(0, builder.length()); digest.reset(); builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8)))); messageDigest = builder.toString(); builder.delete(0, builder.length()); DATE_FORMATTER.formatDate(lastModified, builder); lastModifiedString = builder.toString(); }
From source file:Blowfish.java
/** * Creates a new Blowfish object using the specified key (oversized * password will be cut).// ww w. j ava 2 s . co m * * @param password the password (treated as a real unicode array) */ public Blowfish(String password) { // hash down the password to a 160bit key MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } // setup the encryptor (use a dummy IV) m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java
/** * @see org.apache.ws.security.components.crypto.Crypto#getAliasForX509CertThumb(byte[]) *//*from www . ja v a 2 s. c om*/ public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException { Certificate cert; MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { throw new WSSecurityException(0, "noSHA1availabe"); } try { for (Enumeration e = keystore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = this.getCertificates(alias); if (certs == null || certs.length == 0) { return null; } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError"); } byte[] data = sha.digest(); if (Arrays.equals(data, thumb)) { return alias; } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore"); } return null; }
From source file:org.panbox.desktop.common.sharemgmt.ShareManagerImpl.java
private PanboxShare nameTypeUrlToVolumeData(String shareName, String sharePath, StorageBackendType type, UUID uuid, char[] password) throws IOException, ShareManagerException, ShareMetaDataException, UnrecoverableKeyException { if (!new File(sharePath).exists()) { throw new ShareManagerException( "The specified share path (" + sharePath + ") does not exist or is inaccessible!"); }//from w w w .j a v a2s .co m String metaDataDir = sharePath + File.separator + PanboxConstants.PANBOX_SHARE_METADATA_DIRECTORY + File.separator; File metaDataFile = new File(metaDataDir); File ownerFile = new File(metaDataDir + PanboxConstants.PANBOX_SHARE_OWNER_FILE); String deviceName = Settings.getInstance().getDeviceName(); PanboxShare pbShare = null; // create new share if (!metaDataFile.exists()) { if (password != null) { pbShare = createNewShare(shareName, sharePath, type, password, metaDataFile, ownerFile, deviceName); } else { // empty password field indicates we were trying to load a share // from the DB, but the metadata file was missing throw new ShareInaccessibleException( "Metadatafile for share " + shareName + " could not be found!"); } } else { if (!ownerFile.exists() || !ownerFile.canRead()) { throw new ShareManagerException("Can't access owner file at " + metaDataFile.getAbsolutePath()); } MessageDigest md = getMessageDigestForOwnerFile(); byte[] ownerFp = getOwnerFpFromMessageDigest(ownerFile, md); byte[] me = md.digest(identity.getPublicKeySign().getEncoded()); md.reset(); if (Settings.getInstance().isProtectedDeviceKey()) { password = PasswordEnterDialog.invoke(PasswordEnterDialog.PermissionType.SHARE); } VolumeParams p = paramsFactory.createVolumeParams().setPublicSignatureKey(identity.getPublicKeySign()) .setDeviceAlias(deviceName).setPublicDeviceKey(identity.getPublicKeyForDevice(deviceName)) .setShareName(shareName).setPath(sharePath).setType(type); if (password != null) { // password was entered try { p = p.setPrivateDeviceKey(identity.getPrivateKeyForDevice(password, deviceName)); } catch (UnrecoverableKeyException e) { p = p.setPrivateDeviceKey( identity.getPrivateKeyForDevice(KeyConstants.OPEN_KEYSTORE_PASSWORD, deviceName)); } } else { // password was not entered! Try default one! try { p = p.setPrivateDeviceKey( identity.getPrivateKeyForDevice(KeyConstants.OPEN_KEYSTORE_PASSWORD, deviceName)); // Looks like the configuration of deviceKeyProtection // has been changed! We need to set this option to true // for next startup! Settings.getInstance().setProtectedDeviceKey(false); } catch (UnrecoverableKeyException e) { logger.warn( "Could not get device key with standard password, but standard password was configured."); password = PasswordEnterDialog.invoke(PasswordEnterDialog.PermissionType.SHARE); try { p = p.setPrivateDeviceKey( identity.getPrivateKeyForDevice(KeyConstants.OPEN_KEYSTORE_PASSWORD, deviceName)); // Looks like the configuration of deviceKeyProtection // has been changed! We need to set this option to true // for next startup! Settings.getInstance().setProtectedDeviceKey(true); } catch (UnrecoverableKeyException ex) { logger.error("Entered Password was wrong!"); throw ex; } } } if (Arrays.equals(me, ownerFp)) { // I am the owner try { logger.debug("I am the owner of this preinitialized share, loading..."); pbShare = service.loadShare( p.setOwnerAlias(identity.getEmail()).setOwnerSignatureKey(identity.getPublicKeySign())); } catch (ShareMetaDataException e) { boolean success = false; if (e.getCause() instanceof DeviceKeyException) { // the sharemetadata is ok, but the user's current // device has no keys, possibly because the metadata // state has been reverted due to a file conflict. try // if re-adding the device works, otherwise show error try { logger.warn( "Detected missing device key. This may be because of the metadata state having been reverted due to a file conflict. Will try re-adding the device ...", e); if (password == null) { password = PasswordEnterDialog.invoke(PermissionType.SHARE); } VolumeParams ptmp = paramsFactory.createVolumeParams().setKeys(identity, password) .setUserAlias(identity.getEmail()).setDeviceAlias(deviceName) .setPublicDeviceKey(identity.getPublicKeyForDevice(deviceName)) .setShareName(shareName).setPath(sharePath).setType(type); pbShare = service.addDevice(ptmp); logger.warn("Successfully re-added device key. Trying to re-run loadShare..."); pbShare = service.loadShare(p.setOwnerAlias(identity.getEmail()) .setOwnerSignatureKey(identity.getPublicKeySign())); success = true; } catch (Exception e2) { logger.error("Re-addeding device key failed.", e2); } } // else if (e.getCause() instanceof DeviceListException) { // try { // logger.warn( // "Detected corrupt device list. Will try to reset device list by re-inviting user...", // e); // if (password == null) { // password = PasswordEnterDialog // .invoke(PermissionType.SHARE); // } // // PublicKey pk = ((DeviceListException) e.getCause()) // .getUserKey(); // PanboxContact c = identity.getAddressbook() // .getContactBySignaturePubKey(pk); // // if (c != null) { // logger.warn("DeviceListException associated caused by contact list of contact \"" // + c.getEmail() + "\" "); // // // // VolumeParams pinv = paramsFactory.createVolumeParams() // .setKeys(identity, password) // .setOwnerAlias(identity.getEmail()) // .setOtherSignatureKey(c.getPublicKeySign()) // .setOtherEncryptionKey(c.getPublicKeyEnc()) // .setUserAlias(c.getEmail()) // .setShareName(shareName).setPath(sharePath) // .setType(type); // // // Add Invitation fingerPrint so invited user can detect // // invitation // File invitationFolder = new File(sharePath + // File.separator // + PanboxConstants.PANBOX_SHARE_METADATA_DIRECTORY // + File.separator // + PanboxConstants.PANBOX_SHARE_INVITATION_DIRECTORY); // if (invitationFolder.isFile()) { // // invitationFolder is not a folder // throw new RuntimeException( // "invitation folder is a file, not a folder!"); // } // if (!invitationFolder.exists()) { // invitationFolder.mkdir(); // } // String fingerPrint = DigestUtils.md5Hex(c.getCertSign() // .getPublicKey().getEncoded()); // File fpFile = new File(invitationFolder.getAbsolutePath() // + File.separator + fingerPrint); // fpFile.createNewFile(); // // pbShare = service.inviteUser(p); // pbShare.generatePermissionsModel(identity); // pbShare = pbShare = service.loadShare(p.setOwnerAlias( // identity.getEmail()).setOwnerSignatureKey( // identity.getPublicKeySign())); // // success = true; // } else { // logger.warn("DeviceListException could not be attributed to any existing contact. Publiy Key fingerprint: \"" // + Utils.getPubKeyFingerprint(pk) // + "\" "); // } // // } catch (Exception e2) { // logger.error("Re-inviting user failed.", e2); // } // } if (!success) { logger.error("Unable to load preinitialized share!", e); throw e; } } } else { // I am not the owner IPerson owner = getOwnerForShare(md, ownerFp, p); if (owner != null) { // Found the owner, could be previously initialized share or // a new share that i'm invited to // Is there an invitation for me? File invitationFolder = new File( metaDataDir + PanboxConstants.PANBOX_SHARE_INVITATION_DIRECTORY); String fingerPrint = DigestUtils.md5Hex(identity.getPublicKeySign().getEncoded()); File fpFile = new File(invitationFolder.getAbsolutePath() + File.separator + fingerPrint); if (invitationFolder.isDirectory() && fpFile.isFile()) { // I have been invited to this share // accept invitation and delete invitational // fingerprint pbShare = acceptInvitation(password, deviceName, p); logger.debug("Accepted invitation, deleting invitational fingerprint..."); if (!fpFile.delete()) { logger.warn("Could not delete invitational fingerprint file from invitations folder: " + fpFile.getAbsolutePath()); logger.warn( "If this share is added again it will try to accept an invitation that has already been accepted."); } } else { // There is no invitation for me lying around, so // i'll just assume that this is a previously // existing and correctly initialized share logger.debug("Found owner, assuming preinitialized Share..."); try { pbShare = service.loadShare(p); } catch (ShareMetaDataException e) { boolean success = false; if (e.getCause() instanceof DeviceKeyException) { // the sharemetadata is ok, but the user's // current device has no keys, possibly because // the metadata state has been reverted due to a // file conflict. try if re-adding the device // works, otherwise show error try { logger.warn( "Detected missing device key. This may be because of the metadata state having been reverted due to a file conflict. Will try re-adding the device ...", e); if (password == null) password = PasswordEnterDialog.invoke(PermissionType.SHARE); VolumeParams ptmp = paramsFactory.createVolumeParams() .setKeys(identity, password).setUserAlias(identity.getEmail()) .setDeviceAlias(deviceName) .setPublicDeviceKey(identity.getPublicKeyForDevice(deviceName)) .setShareName(shareName).setPath(sharePath).setType(type); pbShare = service.addDevice(ptmp); logger.warn("Successfully re-added device key. Trying to re-run loadShare..."); pbShare = service.loadShare(p); success = true; } catch (Exception e2) { logger.error("Re-addeding device key failed.", e); } } if (!success) { logger.error("Unable to load preinitialized share!", e); throw e; } } } } else { // The Owner Fingerprint in the share did not match // any of my contacts or myself. Either the real owner is // not in my addressbook, or somebody manipulated the // fingerprint in the share // TODO: if somebody messed with the owner fingerprint // in the share, i could just try to load the share with all // my available contacts and myself as owner and see which // initialization actually runs through throw new UnknownOwnerException("The Owner Fingerprint in the share did not match " + "any of my contacts or myself. Either the real owner is " + "not in my addressbook, or somebody manipulated the " + "fingerprint in the share"); } } // share was loaded successfully - now, we still need to check if // the current users device list has been marked as corrupted. // in this case, accessing the share will fail as no keys will be // available. Thus, an exception needs to be thrown at this point Exception e = null; if ((e = pbShare.getException()) != null) { logger.warn("One or more device lists in share " + pbShare.getName() + " seem to be corrupt... "); if (e instanceof DeviceListException) { DeviceListException ex = (DeviceListException) e; Collection<PublicKey> coll = ex.getUserKeys(); for (Iterator<PublicKey> it = coll.iterator(); it.hasNext();) { PublicKey publicKey = (PublicKey) it.next(); if (Utils.keysEqual(identity.getPublicKeySign(), publicKey)) { // exception was thrown because our own devicelist // was corrupt. this means no sharekey or // obfuscationkeys will be available. logger.fatal("Own device list " + Utils.getPubKeyFingerprint(publicKey) + ".db in share " + pbShare.getName() + " seems to be corrupt. Share will not be available."); throw new ShareMetaDataException("Could not verify signature of device list", ex); } logger.warn("Device list " + Utils.getPubKeyFingerprint(publicKey) + ".db in share " + pbShare.getName() + " seems to be corrupt."); } } } } pbShare.generatePermissionsModel(identity); return pbShare; }
From source file:architecture.common.crypto.Blowfish.java
/** * Creates a new Blowfish object using the specified key (oversized password * will be cut)./*from w ww . java2 s. co m*/ * * @param password * the password (treated as a real unicode array) */ public Blowfish(String password) { // hash down the password to a 160bit key MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { Log.error(e.getMessage(), e); } // setup the encryptor (use a dummy IV) m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java
public static String encrypt(String encryption, String password) throws RaplaException { MessageDigest md; try {//from w ww .j a v a 2 s .c o m md = MessageDigest.getInstance(encryption); } catch (NoSuchAlgorithmException ex) { throw new RaplaException(ex); } synchronized (md) { md.reset(); md.update(password.getBytes()); return encryption + ":" + Tools.convert(md.digest()); } }