Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package cadastrousuario;
- import com.google.gson.Gson;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.Scanner;
- import org.json.JSONObject;
- /**
- *
- * @author RenanTeles
- */
- public class CadastroUsuario {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) throws NoSuchAlgorithmException {
- // TODO code application logic here
- Scanner sc = new Scanner(System.in);
- System.out.println("Cadastre nome do Usuário:");
- String newUser = sc.nextLine();
- System.out.println("Cadastre Senha do Usuário:");
- String newPassword = sc.nextLine();
- String hashSenha = transformaHash(newPassword);
- Usuario user = new Usuario();
- user.setHashSenha(hashSenha);
- user.setNome(newUser);
- JSONObject objeto = new JSONObject();
- objeto.put("nome", user.getNome());
- objeto.put("senha", user.getHashSenha());
- String cadastraUser = new Gson().toJson(objeto);
- saveFileJson(cadastraUser);
- }
- private static String transformaHash(String senha) throws NoSuchAlgorithmException{
- MessageDigest md = MessageDigest.getInstance("MD5");
- md.update(senha.getBytes());
- byte[] hashMd5 = md.digest();
- String hashString = paraStringHexa(hashMd5);
- //System.out.println(hashString);
- String HashFinal = hashString.substring(0, 5);
- //System.out.println(HashFinal);
- return HashFinal;
- }
- private static String paraStringHexa(byte[] bytes) {
- StringBuilder s = new StringBuilder();
- for (int i = 0; i < bytes.length; i++) {
- int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
- int parteBaixa = bytes[i] & 0xf;
- if (parteAlta == 0) s.append('0');
- s.append(Integer.toHexString(parteAlta | parteBaixa));
- }
- return s.toString();
- }
- public static void saveFileJson (String stringJson){
- try {
- File file = new File("cadastroUser.json");
- try (FileWriter fileWriter = new FileWriter(file)) {
- fileWriter.write(stringJson);
- fileWriter.flush();
- }
- } catch (IOException e) {
- }
- }
- // private static gravaTxt(){
- //
- //
- //
- //
- // }
- //
- }
Add Comment
Please, Sign In to add comment