Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package seguranca02;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.math.BigInteger;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.nio.file.StandardOpenOption;
- import java.security.GeneralSecurityException;
- import java.security.InvalidAlgorithmParameterException;
- import java.security.InvalidKeyException;
- import java.security.Key;
- import java.security.KeyStore;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.security.cert.Certificate;
- import java.security.spec.InvalidKeySpecException;
- import java.text.Format;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.List;
- import java.util.Scanner;
- import javax.crypto.BadPaddingException;
- import javax.crypto.Cipher;
- import javax.crypto.CipherInputStream;
- import javax.crypto.CipherOutputStream;
- import javax.crypto.IllegalBlockSizeException;
- import javax.crypto.KeyGenerator;
- import javax.crypto.Mac;
- import javax.crypto.NoSuchPaddingException;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.PBEKeySpec;
- import javax.crypto.spec.PBEParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- import javax.xml.bind.DatatypeConverter;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- import java.util.Collections;
- public class MyGitServerHandler {
- private ObjectOutputStream outStream;
- private ObjectInputStream inStream;
- private String comando;
- private static String passwordDoserver;
- private static final String FILENAME = "Repositorio/utilizadores.txt";
- private static final byte[] SALT = {
- (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
- (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
- };
- private static final byte[] ivBytes = {0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
- 0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
- public MyGitServerHandler(Socket serverSocket,String passwordDoserver) throws IOException, ClassNotFoundException {
- this.inStream=new ObjectInputStream(serverSocket.getInputStream());
- this.outStream= new ObjectOutputStream(serverSocket.getOutputStream());
- this.passwordDoserver=passwordDoserver;
- }
- public String getCommand() {
- return comando;
- }
- public void setCommand(String comando) {
- this.comando=comando;
- }
- public ObjectOutputStream getOutputStream() {
- return outStream;
- }
- public ObjectInputStream getInputStream() {
- return inStream;
- }
- public void closeConnections() throws UnknownHostException, IOException{
- getOutputStream().close();
- getInputStream().close();
- }
- public String ReceberMensagem(){
- try{
- setCommand((String)getInputStream().readObject());
- System.out.println("Mensagem recebida do cliente e "+ getCommand());
- return getCommand();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- return null;
- }
- }
- public void ReceiveToolsAndPull(){
- try{
- String user =(String) this.getInputStream().readObject();
- String name =(String) this.getInputStream().readObject();
- long lastModified= (long) this.getInputStream().readObject();
- File fichServidor = new File("Repositorio/"+name);
- this.getOutputStream().writeBoolean(fichServidor.exists());
- if (fichServidor.exists()){
- //verifica se � um ficheiro
- this.getOutputStream().writeBoolean(fichServidor.isFile());
- if(fichServidor.isFile()){
- //verifica se o fich do servidor � mais recente
- getOutputStream().writeBoolean(lastModified < fichServidor.lastModified());
- if (lastModified < fichServidor.lastModified()){
- //envia o last modified do servidor
- this.getOutputStream().writeObject(fichServidor.lastModified());
- getOutputStream().flush();
- //envia ficheiro para o servidor
- //Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
- EnviarFicheiro(fichServidor, false);
- }else{
- System.out.println("O ficheiro local � mais recente que o do servidor");
- }
- }else{
- this.getOutputStream().writeObject(listaNomesFicheiros(fichServidor));
- this.getOutputStream().flush();
- EnviarDiretoria(fichServidor);
- }
- }else{
- System.out.println("O ficheiro nao existe no servidor");
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public void ReceiveToolsAndPush(){
- try{
- ///ferramentas
- String user =(String) this.getInputStream().readObject();
- String name =(String) this.getInputStream().readObject();
- boolean isFile = (boolean) this.getInputStream().readObject();
- long lastModified= (long) this.getInputStream().readObject();
- //ferramentas fim
- File fichServidor = new File("Repositorio/"+user+"/"+name);
- //2 parte
- if (fichServidor.exists()){
- if (isFile){
- //tratar ficheiro parte 1
- System.out.println("tratar ficheiro parte 1");
- Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
- Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
- Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
- }else{
- //se � mais recente
- getOutputStream().writeBoolean(lastModified > fichServidor.lastModified());
- getOutputStream().flush();
- List<String> listaNomes= null;
- listaNomes = (List<String>) getInputStream().readObject();
- TreatDirectory(name, lastModified, fichServidor, listaNomes, user);
- }
- }else{
- if (isFile){
- //isto nao estava no trabalho e se nao estiver da Erro
- System.out.println("tratar ficheiro parte 1");
- File pastaUser = new File("Repositorio/"+user);
- if (!(pastaUser.exists()))
- pastaUser.mkdirs();
- //O codigo que falta � at� aqui
- Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".sig", lastModified, fichServidor, Long.MIN_VALUE );
- Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".key", lastModified, fichServidor, Long.MIN_VALUE );
- Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".cif", lastModified, fichServidor, Long.MIN_VALUE );
- }else{
- getOutputStream().writeBoolean(lastModified > fichServidor.lastModified());
- getOutputStream().flush();
- //se � mais recente
- List<String> listaNomes =(List<String>) getInputStream().readObject();
- TreatDirectory(name, lastModified, fichServidor, listaNomes, user);
- }
- }
- //2 parte fim
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public void Verifica_Recebe(String nome_ficheiro, long fichLastModified, File fichServidor, long fichServerLastMod) throws Exception{
- if (fichServidor.exists() && fichLastModified > fichServerLastMod ){
- //tratar ficheiro parte 2
- System.out.println("tratar ficheiro parte 2");
- getOutputStream().writeBoolean(true);
- getOutputStream().flush();
- String[] nomePartido = nome_ficheiro.split("\\.(?=[^\\.]+$)");
- Date d = new Date(fichServidor.lastModified());
- Format formatter = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
- File newVersion;
- if (nomePartido.length<2){
- newVersion = new File("Repositorio/"+nomePartido[0]+"versao_"+formatter.format(d));
- }else{
- newVersion = new File("Repositorio/"+nomePartido[0]+"versao_"+formatter.format(d)+"."+nomePartido[1]);
- }
- if (newVersion.exists())
- throw new java.io.IOException("file exists");
- // Rename file (or directory)
- fichServidor.renameTo(newVersion);
- ReceberFicheiro(nome_ficheiro, fichLastModified);
- System.out.println("O ficheiro "+nome_ficheiro+" foi enviado para o servidor");
- //fazer aqui um write
- getOutputStream().writeObject("O ficheiro "+fichServidor.getName()+" foi enviado para o servidor");
- }
- else if(!fichServidor.exists()){
- System.out.println("tratar ficheiro parte 2");
- //tratar ficheiro parte 2
- getOutputStream().writeBoolean(true);
- getOutputStream().flush();
- ReceberFicheiro(nome_ficheiro, fichLastModified );
- System.out.println("O ficheiro "+nome_ficheiro+" foi enviado para o servidor");
- //fazer aqui um write
- getOutputStream().writeObject("O ficheiro "+fichServidor.getName()+" foi enviado para o servidor");
- }else{
- System.out.println("tratar ficheiro parte 2");
- //tratar ficheiro parte 2
- getOutputStream().writeBoolean(fichLastModified > fichServerLastMod);
- getOutputStream().flush();
- System.out.println("O servidor ja tem o ficheiro mais recente");
- }
- }
- public void TreatDirectory(String name, long dirLastModified, File dirServidor, List<String> listaNomes, String user){
- try{
- //se diretoria existe faz below
- if (dirServidor.exists()){
- // this.getOutputStream().writeBoolean(false);
- List<String> listaServidor = new ArrayList<String>();
- for(File i : dirServidor.listFiles()){
- System.out.println("Nome do ficheiro--------->>"+i.getName());
- listaServidor.add(i.getName());
- }
- RemoverFicheiros(listaServidor,listaNomes, name, user);
- for(String ficheiroNaDir : listaNomes){
- File file= new File("Repositorio/"+user+"/"+dirServidor.getName()+"/"+ficheiroNaDir);
- Long lastMod = (Long) getInputStream().readObject();
- if(lastMod.longValue()>file.lastModified()){
- getOutputStream().writeBoolean(true);
- getOutputStream().flush();
- Verifica_Recebe(user+"/"+dirServidor.getName()+"/"+ficheiroNaDir, lastMod.longValue(), file , file.lastModified());
- }else{
- getOutputStream().writeBoolean(false);
- getOutputStream().flush();
- System.out.println("O ficheiro do servidor � mais recente");
- }
- }
- this.getOutputStream().writeObject("O ficheiro "+dirServidor.getName()+" foi enviado para o servidor");
- }else if(!dirServidor.exists()){
- dirServidor.mkdirs();
- // this.getOutputStream().writeBoolean(true);
- // this.getOutputStream().writeObject("O ficheiro "+dirServidor.getName()+" foi criado no servidor");
- PrintWriter writer = new PrintWriter("Repositorio/"+user+"/"+dirServidor.getName()+"/shareFilesUsers.txt", "UTF-8");
- writer.println(user);
- writer.close();
- for(String ficheiroNaDir : listaNomes){
- File file= new File("Repositorio/"+dirServidor.getName()+"/"+ficheiroNaDir);
- long lastMod = (long) getInputStream().readObject();
- Verifica_Recebe(user+"/"+name+"/"+ficheiroNaDir,lastMod, file, file.lastModified());
- }
- }else{
- // this.getOutputStream().writeBoolean(true);
- // this.getOutputStream().writeObject("Ficheiro do servidor � mais recente que o local");
- System.out.println("Ficheiro do servidor � mais recente que o local");
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public boolean Authentication() throws ClassNotFoundException, IOException{
- try {
- decriptado();
- File file = new File("Repositorio/utilizadores.txt");
- FileReader fr = new FileReader(file);
- BufferedReader br = new BufferedReader(fr);
- String sCurrentLine;
- String name =(String) getInputStream().readObject();
- String nounce = SendNounce();
- getOutputStream().writeObject(nounce);
- getOutputStream().flush();
- String passwordfinal = (String) getInputStream().readObject();
- boolean flag=true;
- boolean response=true;
- while ((sCurrentLine = br.readLine()) != null) {
- if (sCurrentLine.split(":")[0].equals(name)){
- flag=false;
- System.out.println(passwordfinal);
- System.out.println(DoMAC(nounce+sCurrentLine.split(":")[1]));
- if (DoMAC(nounce+sCurrentLine.split(":")[1]).equals(passwordfinal)){
- getOutputStream().writeBoolean(false);
- getOutputStream().writeObject("A password est� correcta");
- getOutputStream().flush();
- getOutputStream().writeBoolean(true);
- getOutputStream().flush();
- br.close();
- fr.close();
- response=true;
- break;
- }else{
- getOutputStream().writeBoolean(false);
- getOutputStream().writeObject("A est� password incorrecta,desligando este cliente");
- getOutputStream().flush();
- getOutputStream().writeBoolean(false);
- getOutputStream().flush();
- br.close();
- fr.close();
- response=false;
- break;
- }
- }
- }
- if (flag){
- getOutputStream().writeBoolean(true);
- getOutputStream().flush();
- String password = (String) getInputStream().readObject(); // so manda em claro senao existir
- if(getInputStream().readBoolean()){
- CreateUser("Repositorio/utilizadores.txt", name, password);
- getOutputStream().writeObject("O utilizador "+name+" foi criado");
- getOutputStream().flush();
- }else{
- getOutputStream().writeObject("As passwords n�o s�o iguais");
- getOutputStream().flush();
- response=false;
- }
- }
- br.close();
- fr.close();
- encriptado();
- return response;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- private void CreateUser(String writeFile, String name, String password) {
- try {
- Files.write(Paths.get(writeFile), ("\n"+name+":"+password).getBytes(), StandardOpenOption.APPEND);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void Verifica_Envia(String nome_ficheiro, long fichLastModified) throws Exception{
- File fichServidor = new File("Repositorio/"+nome_ficheiro);
- long fichServidorLastModified = fichServidor.lastModified();
- if (fichServidor.exists() && fichLastModified < fichServidorLastModified ){
- getOutputStream().writeObject((fichLastModified < fichServidorLastModified));
- getOutputStream().writeObject(fichServidorLastModified);
- getOutputStream().flush();
- EnviarFicheiro(fichServidor, false);
- //ReceberFicheiro(nome_ficheiro, fichLastModified);
- System.out.println("o ficheiro "+nome_ficheiro+" foi enviado para o cliente");
- }
- else if(!fichServidor.exists()){
- getOutputStream().writeObject(true);
- getOutputStream().flush();
- ReceberFicheiro(nome_ficheiro, fichLastModified );
- }else{
- getOutputStream().writeObject((fichLastModified > fichServidor.lastModified()));
- getOutputStream().flush();
- System.out.println("O servidor ja tem o ficheiro mais recente");
- }
- }
- public void ReceberFicheiro (String nome_ficheiro, long fichLastModified) throws Exception{
- System.out.println("ele existe---->"+"Repositorio/"+nome_ficheiro);
- FileOutputStream fileOutput = new FileOutputStream("Repositorio/"+nome_ficheiro);
- BufferedOutputStream fileBuffer = new BufferedOutputStream(fileOutput);
- int size = getInputStream().readInt();
- System.out.println("ele existe FIM---->"+"Repositorio/"+nome_ficheiro);
- int n;
- int lidos=0;
- byte[] buffer = new byte[1024];
- while(lidos < (int) size){
- n= getInputStream().read(buffer,0,size-lidos<1024? size-lidos:1024);
- fileOutput.write(buffer,0,n);
- fileOutput.flush();
- lidos+=n;
- }
- new File("Repositorio/"+nome_ficheiro).setLastModified(fichLastModified);
- fileBuffer.close();
- fileOutput.close();
- // CifrarChaveComChavePublica(nome_ficheiro);
- // if (nome_ficheiro.split("\\.(?=[^\\.]+$)")[1].equals("txt")) {
- // File file=new File("Repositorio/"+nome_ficheiro);
- // file.delete();
- // }
- }
- public void RemoverFicheiros(List<String> listaServidor,List<String> listaNomes, String name, String user) throws IOException{
- List<String> listaParaRemover = new ArrayList<String>();
- for(String j : listaServidor){
- if (listaNomes!=null && listaNomes.indexOf(j)==-1 && !(j.equals("shareFilesUsers.txt")) && j.indexOf("versao_")==-1){
- System.out.println("Ficheiros a remover-----> "+j);
- listaParaRemover.add(j);
- }
- }
- for (String aRemover : listaParaRemover){
- File fichParaRemover = new File("Repositorio/"+user+"/"+name+"/"+aRemover);
- String[] nomePartido = fichParaRemover.getName().split("\\.(?=[^\\.]+$)");
- Date d = new Date(fichParaRemover.lastModified());
- Format formatter = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
- File newVersion = new File("Repositorio/"+user+"/"+name+"/"+nomePartido[0]+"versao_"+formatter.format(d)+"."+nomePartido[1]);
- if (newVersion.exists())
- throw new java.io.IOException("file exists");
- // Rename file (or directory)
- fichParaRemover.renameTo(newVersion);
- }
- }
- public void EnviarFicheiro(File file, boolean isDirectory) throws IOException {
- if (isDirectory){
- this.getOutputStream().writeObject(new Long(file.lastModified()));
- getOutputStream().flush();
- if(!getInputStream().readBoolean()){
- System.out.println("O servidor j� tem a vers�o mais recente!!");
- return;
- }
- }
- getOutputStream().writeInt((int)file.length());
- System.out.println("7-----len do file--> "+ file.length());
- FileInputStream fileInputStream = new FileInputStream(file);
- BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
- int n;
- byte[] buffer = new byte[1024];
- while((n=bufferedInputStream.read(buffer, 0, 1024))!=-1){
- getOutputStream().write(buffer,0,n);
- getOutputStream().flush();
- }
- //System.out.println("resultado do servidor: "+String.valueOf(inputStream.readObject())); //mensagem do servidor
- bufferedInputStream.close();
- fileInputStream.close();
- }
- public void ShareRep() throws ClassNotFoundException, IOException, InvalidKeyException, NoSuchAlgorithmException{
- String nameDir = (String) this.getInputStream().readObject();
- String owner = (String) this.getInputStream().readObject();
- String userToAdd = (String) this.getInputStream().readObject();
- File file = new File("Repositorio/"+owner+"/"+nameDir+"/shareFilesUsers.txt"); // creates the file
- VerificaMACForShare(passwordDoserver,owner,nameDir);
- DoMACforShare(passwordDoserver,owner,nameDir);
- if (CheckUser(userToAdd, new File("Repositorio/utilizadores.txt"))){
- if(CheckOwner(owner, file)){
- FileWriter writer = new FileWriter(file, true); // Writes the content to the file
- if (!IsInFile(file, userToAdd)){
- writer.append("\n"+userToAdd);
- writer.flush();
- }else{
- System.out.println("O utilizador a que pretende fazer a partilha do reposit�rio, j� tem permiss�o para aceder a pasta");
- }
- writer.close();
- }else{
- System.out.println("O utilizador n�o tem permiss�o para fazer share deste reposit�rio");
- }
- }else{
- System.out.println("Erro: O utilizador "+userToAdd+" n�o existe");
- }
- }
- public void RemovePermisson() throws ClassNotFoundException, IOException{
- String nameDir = (String) this.getInputStream().readObject();
- String owner = (String) this.getInputStream().readObject();
- String userToRemove = (String) this.getInputStream().readObject();
- File file = new File("Repositorio/"+owner+"/"+nameDir+"/shareFilesUsers.txt"); // creates the file
- if (CheckUser(userToRemove, file)){
- if(CheckOwner(owner, file)){
- if (IsInFile(file, userToRemove)){
- RemoverLinha(userToRemove,file);
- }else{
- System.out.println("O utilizador a que pretende fazer a partilha do reposit�rio, j� tem permiss�o para aceder a pasta");
- }
- }else{
- System.out.println("O utilizador n�o tem permiss�o para fazer share deste reposit�rio");
- }
- }
- }
- public boolean IsInFile(File file,String string) {
- try {
- Scanner scanner = new Scanner(file);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- if(line.equals(string)) {
- scanner.close();
- return true;
- }
- }
- scanner.close();
- return false;
- } catch(FileNotFoundException e) {
- //handle this
- }
- return false;
- }
- public boolean CheckOwner(String owner, File file) throws IOException{
- BufferedReader test = new BufferedReader(new FileReader(file));
- String text = test.readLine();
- if (text.equals(owner)){
- test.close();
- return true;
- }
- test.close();
- return false;
- }
- public boolean CheckUser(String user, File file) throws IOException{
- try{
- FileReader fr = new FileReader(file);
- BufferedReader br = new BufferedReader(fr);
- String sCurrentLine;
- while ((sCurrentLine = br.readLine()) != null) {
- //System.out.println(sCurrentLine+ "scurrentline");
- if (sCurrentLine.split(":")[0].equals(user)){
- return true;
- }
- }
- br.close();
- fr.close();
- return false;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- public boolean RemoverLinha(String username,File filename) throws IOException {
- BufferedReader reader = new BufferedReader(new FileReader(filename));
- File tempFile = new File("shareFilesUsers.txt");
- BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
- String lineToRemove = username;
- String currentLine;
- while((currentLine = reader.readLine()) != null) {
- // trim newline when comparing with lineToRemove
- String trimmedLine = currentLine.trim();
- if(trimmedLine.equals(lineToRemove)) continue;
- writer.write(currentLine + System.getProperty("line.separator"));
- }
- writer.close();
- reader.close();
- boolean successful = tempFile.renameTo(filename);
- return successful;
- }
- public List<String> listaNomesFicheiros(File file) throws IOException{
- List<String> listaNomes = new ArrayList<String>();
- for (File i : file.listFiles()){
- if (!i.getName().equals(".DS_Store") && !i.getName().equals("shareFilesUsers.txt"))
- listaNomes.add(i.getName());
- }
- return listaNomes;
- }
- public void EnviarDiretoria(File dir) throws IOException {
- File[] listaNomes = dir.listFiles();
- for (File ficheiro : listaNomes) {
- if (!ficheiro.getName().equals(".DS_Store") && !ficheiro.getName().equals("shareFilesUsers.txt"))
- EnviarFicheiro(ficheiro,true);
- }
- }
- public String SendNounce() throws NoSuchAlgorithmException, IOException {
- SecureRandom random = new SecureRandom();
- String nounce = new BigInteger(256,random).toString();
- return nounce;
- }
- public String DoMAC(String passwd) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
- Mac mac = Mac.getInstance("HmacSHA256");
- byte [] pass = passwd.getBytes();
- SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
- mac.init(key);
- return DatatypeConverter.printHexBinary(mac.doFinal());
- }
- public static void DoMACforShare(String passwd,String owner,String namedir) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
- try (BufferedWriter bw = new BufferedWriter(new FileWriter("Repositorio/"+owner+"/"+namedir+"/ShareMACFile"))) {
- Mac mac = Mac.getInstance("HmacSHA256");
- byte [] pass = passwd.getBytes();
- byte[] bFile = Files.readAllBytes(Paths.get("Repositorio/"+owner+"/"+namedir+"/shareFilesUsers.txt"));
- SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
- mac.init(key);
- mac.update(bFile);
- bw.write(DatatypeConverter.printHexBinary(mac.doFinal()));
- bw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void VerificaMACForShare(String passwd,String owner,String namedir) throws NoSuchAlgorithmException, IOException, InvalidKeyException {
- Mac mac = Mac.getInstance("HmacSHA256");
- byte[] pass = passwd.getBytes();
- SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
- mac.init(key);
- FileReader fr = new FileReader("Repositorio/"+owner+"/"+namedir+"/ShareMACFile");
- BufferedReader br = new BufferedReader(fr);
- String s;
- while((s = br.readLine()) != null) {
- if(s.equals(DatatypeConverter.printHexBinary(mac.doFinal()))) {
- System.out.println(s);
- System.out.println(DatatypeConverter.printHexBinary(mac.doFinal()));
- }
- else {
- System.out.println("Ficheiro MAC corrompido, desligando o servidor ");
- System.exit(-1);
- }
- }
- fr.close();
- }
- private static byte[] encriptado() throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
- PBEKeySpec keySpec = new PBEKeySpec(passwordDoserver.toCharArray());
- SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
- SecretKey key = kf.generateSecret(keySpec);
- IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
- PBEParameterSpec spec = new PBEParameterSpec(SALT, 20, ivSpec);
- Path path = Paths.get("Repositorio/utilizadores.txt");
- byte[] data = Files.readAllBytes(path);
- Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
- c.init(Cipher.ENCRYPT_MODE, key, spec);
- FileOutputStream fos = new FileOutputStream("Repositorio/utilizadores.txt");
- fos.write(c.doFinal(data));
- fos.close();
- return c.doFinal();
- }
- private static byte[] decriptado() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
- PBEKeySpec keySpec = new PBEKeySpec(passwordDoserver.toCharArray());
- SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
- SecretKey key = kf.generateSecret(keySpec);
- IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
- PBEParameterSpec spec = new PBEParameterSpec(SALT, 20, ivSpec);
- Path path = Paths.get("Repositorio/utilizadores.txt");
- byte[] data = Files.readAllBytes(path);
- Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
- c.init(Cipher.DECRYPT_MODE, key, spec);
- FileOutputStream fos = new FileOutputStream("Repositorio/utilizadores.txt");
- fos.write(c.doFinal(data));
- fos.close();
- return c.doFinal(data);
- }
- // public static void CifrarChaveComChavePublica(String keyname) throws Exception {
- // //gerar uma chave aleat�ria para utilizar com o AES
- // KeyGenerator kg = KeyGenerator.getInstance("AES");
- // kg.init(128);
- // SecretKey key = kg.generateKey();
- // Cipher c = Cipher.getInstance("AES");
- // c.init(Cipher.ENCRYPT_MODE, key);
- //
- // FileInputStream fis;
- // // FileOutputStream fos;
- // // CipherOutputStream cos;
- //
- // fis = new FileInputStream("Repositorio/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".key");
- //
- // FileInputStream fileInputStream = new FileInputStream("Repositorio/key.file"); // chave do server
- // KeyStore keyStore = KeyStore.getInstance("JKS");
- // keyStore.load(fileInputStream, "trotinete96".toCharArray());
- // Certificate certificate = keyStore.getCertificate("seguranca02"); // para ir buscar o certificado e chave publica
- //
- //
- // Cipher ckey = Cipher.getInstance("RSA");
- // ckey.init(Cipher.WRAP_MODE, certificate);
- //
- // byte[] chaveCifrada = ckey.wrap(key);
- //
- // FileOutputStream kos = new FileOutputStream("Repositorio/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server");
- // kos.write(chaveCifrada);
- // kos.close();
- // fis.close();
- //
- //
- // }
- // public static void DecifrarChave(String user,String keyname) throws Exception {
- // File file = new File("Repositorio/"+user+"/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server"); // chave cifrada do cliente com a minha privada
- // FileInputStream kos = new FileInputStream(file);
- //
- // byte[] chaveCifrada = new byte[256];
- // int i = kos.read(chaveCifrada);
- //
- // FileInputStream fileInputStream = new FileInputStream("Repositorio/key.file");
- // KeyStore keyStore = KeyStore.getInstance("JKS");
- // keyStore.load(fileInputStream, "trotinete96".toCharArray());
- // Key privateKey = keyStore.getKey("seguranca02", "trotinete96".toCharArray());
- //
- // Cipher c = Cipher.getInstance("RSA");
- // c.init(Cipher.UNWRAP_MODE, privateKey );
- // Key s = c.unwrap(chaveCifrada, "AES", Cipher.SECRET_KEY);
- // System.out.println(s);
- // Cipher c1 = Cipher.getInstance("AES");
- // c1.init(Cipher.DECRYPT_MODE, s);
- // System.out.println(c1.doFinal());
- // FileOutputStream fos = new FileOutputStream("pathnamecaralho");
- // fos.write(c1.doFinal());
- // fos.close();
- // }
- }
- // Cipher c1 = Cipher.getInstance("AES");
- // c1.init(Cipher.DECRYPT_MODE, s);
- //
- //
- // FileInputStream cos = new FileInputStream("a.txt");
- //
- // CipherInputStream asduos = new CipherInputStream(cos, c1);
- // File file2 = new File("b.txt");
- // FileOutputStream fileOutputStream = new FileOutputStream(file2);
- //
- //
- //
- // int size = asduos.read(chaveCifrada);
- // byte[] byt = new byte[16];
- // while (size != -1) {
- // fileOutputStream.write(chaveCifrada, 0, size);
- // fileOutputStream.flush();
- // size = asduos.read(chaveCifrada);
- // }
- // fileOutputStream.close();
- // kos.close();
- // cos.close();
- // asduos.close();
- // }
- // }
- // public static void DecifrarFile(String filename) throws Exception {
- // File file = new File("Repositorio/"+filename.split("\\.(?=[^\\.]+$)")[0]+".key");
- // FileInputStream kos = new FileInputStream(file);
- //
- // byte[] chaveCifrada = new byte[256];
- // int i = kos.read(chaveCifrada);
- //
- //
- // FileInputStream fileInputStream = new FileInputStream("Repositorio/key.file");
- // KeyStore keyStore = KeyStore.getInstance("JKS");
- // keyStore.load(fileInputStream, "trotinete96".toCharArray());
- // Key privateKey = keyStore.getKey("seguranca02", "trotinete96".toCharArray());
- //
- // Cipher c = Cipher.getInstance("RSA");
- // c.init(Cipher.UNWRAP_MODE, privateKey );
- //
- //
- // Key s = c.unwrap(chaveCifrada, "AES", Cipher.SECRET_KEY);
- //
- // Cipher c1 = Cipher.getInstance("AES");
- // c1.init(Cipher.DECRYPT_MODE, s);
- //
- // FileInputStream cos = new FileInputStream("Repositorio/"+filename.split("\\.(?=[^\\.]+$)")[0]+".cif");
- // CipherInputStream asduos = new CipherInputStream(cos, c1);
- // File file2 = new File("Repositorio/teste.txt");
- // FileOutputStream fileOutputStream = new FileOutputStream(file2);
- //
- //
- // int size = asduos.read(chaveCifrada);
- // byte[] byt = new byte[16];
- // while (size != -1) {
- // fileOutputStream.write(chaveCifrada, 0, size);
- // fileOutputStream.flush();
- // size = asduos.read(chaveCifrada);
- // }
- // //bufferedOutputStream.close();
- // fileOutputStream.close();
- // kos.close();
- // //bos.close();
- // cos.close();
- // asduos.close();
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement