Skip to content

Commit

Permalink
comunicação com certificado digital
Browse files Browse the repository at this point in the history
  • Loading branch information
TroniPM committed Dec 4, 2017
1 parent f0530a7 commit 59858f9
Show file tree
Hide file tree
Showing 15 changed files with 223 additions and 141 deletions.
2 changes: 1 addition & 1 deletion nbproject/private/private.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ do.depend=false
do.jar=true
javac.debug=true
javadoc.preview=true
user.properties.file=C:\\Users\\Matt\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
user.properties.file=C:\\Users\\Mateus\\AppData\\Roaming\\NetBeans\\8.1\\build.properties
Binary file added private_this.stopdonha
Binary file not shown.
Binary file added public_this.stopdonha
Binary file not shown.
6 changes: 0 additions & 6 deletions src/entidades/GameRuntime.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@
import java.util.Collections;
import java.util.Comparator;
import entidades.network.sendible.User;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import util.Session;

/**
Expand Down
3 changes: 0 additions & 3 deletions src/entidades/network/Cliente.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
import entidades.network.sendible.EndRoundArray;
import entidades.network.sendible.User;
import entidades.network.sendible.UserArray;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.SecretKey;
Expand All @@ -27,7 +25,6 @@
import security.KeyAutenticacaoServidor;
import security.KeyEncriptacaoCliente;
import security.KeyEncriptacaoServidor;
import util.Methods;
import util.Session;

/**
Expand Down
6 changes: 2 additions & 4 deletions src/entidades/network/Servidor.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@
import entidades.network.sendible.User;
import entidades.network.sendible.UserArray;
import java.io.ObjectOutputStream;
import java.net.SocketException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.net.SocketException;
import java.security.PrivateKey;
import java.util.List;
import javax.crypto.SecretKey;
import org.apache.commons.lang3.SerializationUtils;
Expand Down
6 changes: 0 additions & 6 deletions src/entidades/network/sendible/User.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
package entidades.network.sendible;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;
Expand Down
143 changes: 74 additions & 69 deletions src/security/Security.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package security;

import java.security.SecureRandom;
import java.io.File;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
Expand All @@ -13,31 +12,24 @@
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import entidades.network.sendible.User;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import org.apache.commons.lang3.SerializationUtils;
import util.Methods;
import util.Session;

/**
Expand All @@ -46,20 +38,21 @@
*/
public class Security {

public static final String chave_this_public_path = "./public_this.stopdonha";
public static final String chave_this_private_path = "./private_this.stopdonha";
public static final String chave_server_public_path = "./public_server.stopdonha";

//public static final String chave_this_public_path = "./public_this.stopdonha";
//public static final String chave_this_private_path = "./private_this.stopdonha";
//public static final String chave_server_public_path = "./certificate/self_public.cer";
private static final String param1 = "RSA";

public PublicKey chavePublicaSERVIDOR = null;
public PublicKey chavePublicaTHIS = null;
//public PublicKey chavePublicaTHIS = null;
public PrivateKey chavePrivadaTHIS = null;

public String TAG = null;
public int TAG_NUMBER = 1;

public ChaveSessao KEY;
public static File certificado = null;
public static String certificadoSenha = null;

public byte[] criptografaSimetrica(byte[] data, SecretKey secret) {
try {
Expand Down Expand Up @@ -192,60 +185,9 @@ public void init() throws UnknownHostException {

TAG = Inet4Address.getLocalHost().getHostAddress();
TAG_NUMBER = 0;

Session.addLog("Criação de chaves pública/privada...");
if (Methods.fileExists(chave_this_public_path) && Methods.fileExists(chave_this_private_path)) {
Session.addLog("Chaves já existem. Recuperando chaves...");
try {
chavePublicaTHIS = (PublicKey) SerializationUtils.
deserialize(Methods.readFileBytes(chave_this_public_path));
chavePrivadaTHIS = (PrivateKey) SerializationUtils.
deserialize(Methods.readFileBytes(chave_this_private_path));
System.out.println(chavePublicaTHIS);
Session.addLog("Chaves foram recuperadas com sucesso...");
} catch (Exception ex) {
Session.addLog("Erro ao recuperar chaves. Irá criar novas chaves do zero...");
createKeys();
}
} else {
Session.addLog("Chaves não existem. Criar novas chaves...");
createKeys();
}

//Recuperando chave do servidor
Session.addLog("Tentando recuperar chave pública do servidor...");
if (Methods.fileExists(chave_server_public_path)) {
Session.addLog("Chave pública do servidor existe...");
try {
chavePublicaSERVIDOR = (PublicKey) SerializationUtils.
deserialize(Methods.readFileBytes(chave_server_public_path));
System.out.println(chavePublicaSERVIDOR);
Session.addLog("Chave pública recuperada...");
} catch (Exception ex) {
Session.addLog("Erro ao recuperar chave do servidor. Não permitir acesso a rede.");
}
} else {
Session.addLog("Chave pública do servidor não existe. Não permitir acesso a rede.");
}
}

private void createKeys() {
KeyPairGenerator assimetrica = null;
try {
assimetrica = KeyPairGenerator.getInstance("RSA", "BC");
assimetrica.initialize(2048, new SecureRandom());
} catch (Exception e) {
e.printStackTrace();
}
KeyPair keyPair = assimetrica.generateKeyPair();
chavePublicaTHIS = keyPair.getPublic();
chavePrivadaTHIS = keyPair.getPrivate();

Methods.writeOnFile(chave_this_public_path, SerializationUtils.serialize(chavePublicaTHIS), false);
Methods.writeOnFile(chave_this_private_path, SerializationUtils.serialize(chavePrivadaTHIS), false);
}

public static PrivateKey getPrivateKeyFromCert(String path, String senha) {
public PrivateKey getPrivateKeyFromCert(String path, String senha) {
PrivateKey pKey = null;
try {
KeyStore p12 = KeyStore.getInstance("pkcs12");
Expand All @@ -269,7 +211,7 @@ public static PrivateKey getPrivateKeyFromCert(String path, String senha) {
return pKey;
}

public static PublicKey getPublicKeyFromCert(String path) {
public PublicKey getPublicKeyFromCert(String path) {
PublicKey pk = null;
try {
FileInputStream fin = new FileInputStream(path);
Expand All @@ -284,9 +226,72 @@ public static PublicKey getPublicKeyFromCert(String path) {
return pk;
}

public PublicKey getPublicKeyFromCert(File path) {
PublicKey pk = null;
try {
FileInputStream fin = new FileInputStream(path);
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) f.generateCertificate(fin);
pk = certificate.getPublicKey();
} catch (Exception ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
}
return pk;
}

public boolean checkPasswordFromCert(String path, String senha) {
PrivateKey pKey = null;
try {
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream(path), senha.toCharArray());
Enumeration e = p12.aliases();
String alias = (String) e.nextElement();
pKey = (PrivateKey) p12.getKey(alias, senha.toCharArray());

if (pKey != null) {
return true;
}

} catch (KeyStoreException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
}

return false;
}

public boolean checkValidity(String path, String senha) {
try {
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream(path), senha.toCharArray());
Enumeration e = p12.aliases();
String alias = (String) e.nextElement();
/*if (p12.getCertificate(alias).getType().equals("X.509")) {
System.out.println(alias + " expires "
+ ((X509Certificate) p12.getCertificate(alias)).getNotAfter());
}*/

//Date d = new Date();
//d.setYear(2030);
((X509Certificate) p12.getCertificate(alias)).checkValidity();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

public static void main(String[] args) {
PrivateKey privateKeyFromCert = getPrivateKeyFromCert("./certificate/self_pkcs12.p12", "password");
PublicKey publicKeyFromCert = getPublicKeyFromCert("./certificate/self_public.cer");
Security s = new Security();
PrivateKey privateKeyFromCert = s.getPrivateKeyFromCert("./certificate/self_pkcs12.p12", "password");
PublicKey publicKeyFromCert = s.getPublicKeyFromCert("./certificate/self_public.cer");

String a = "texto1 normal a ser encriptadoáéíóLoÇô";
System.out.println("NORMAL: " + a);
Expand Down
17 changes: 15 additions & 2 deletions src/ui/GameScreenConfigGame.form
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="180" y="410" width="80" height="40"/>
<AbsoluteConstraints x="150" y="410" width="80" height="40"/>
</Constraint>
</Constraints>
</Component>
Expand Down Expand Up @@ -492,7 +492,20 @@
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="460" y="410" width="80" height="40"/>
<AbsoluteConstraints x="480" y="410" width="80" height="40"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="jButton3">
<Properties>
<Property name="text" type="java.lang.String" value="Selecionar certificado"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton3ActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="270" y="410" width="170" height="40"/>
</Constraint>
</Constraints>
</Component>
Expand Down
Loading

0 comments on commit 59858f9

Please sign in to comment.