* Datos del Taller
- Nombre del Taller :: Introducción a la criptografía
- Reseña :: Mostrar los principios básicos de la criptografía desde un punto de vista práctico y teórico. Se pretende que el participante comprenda el uso, las aplicaciones, la importancia y las herramientas que actualmente se disponen para realizar las tareas básicas de cifrado. También, se describirán algunas interfaces de programación en algunos lenguajes para llevar a cabo estas tareas. Finalmente, se mostrarán ejemplos de aplicación para que se pueda observar la importancia en cuanto a la seguridad y privacidad de la información.
- Requisitos para el Taller :: GNU/Linux instalado o el paquete GPG2 desde https://www.gnupg.org para el sistema operativo que posea.
- Short Bio :: Docente en la Universidad Nacional del Comahue y recibido como Licenciado en Ciencias de la Computación de dicha institución. Integro el Grupo de Investigación de Lenguajes e Inteligencia Artificial (GILIA) el cual estoy involucrado en el desarrollo de herramientas Web para la Web Semántica. Además, soy parte del Grupo de Usuario de Lignux de Allen (ULA) con los que comparto afición por el Software Libre, la computación y la electrónica.
- Nombre del que da el taller :: Christian Gimenez
** Licencias
En esta sección se indica la licencia de este documento y de los archivos que puede generar.
*** Este Documento (DevFest2018.org)
Este documento está bajo la licencia GPLv3.
Copyright 2018 Christian Gimenez
Author: Christian Gimenez
DevFest2018.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*** Archivos Python Generados
#+begin_src python :tangle gpgEj1.py
# -*- coding: utf-8 -*-
'''
GNU GPG Ejemplo de uso.
:copyright: 2018 Christian Gimenez
:author: Christian Gimenez
:license: GPL v3 (see COPYING.txt or LICENSE.txt file for more information)
'''
#
# gpgEj1.py
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#+end_src
#+begin_src python :tangle gnupgEj2.py
# -*- coding: utf-8 -*-
'''
GNU GPG Ejemplo de uso.
:copyright: 2018 Christian Gimenez
:author: Christian Gimenez
:license: GPL v3 (see COPYING.txt or LICENSE.txt file for more information)
'''
#
# gnupgEj2.py
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#+end_src
*** Archivos Ruby Generados
#+begin_src ruby :tangle gpgme.rb
# -*- coding: utf-8 -*-
#
# Copyright 2018 Christian Gimenez
#
# Author: Christian Gimenez
#
# gpgme.rb
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#+end_src
*** Archivos PHP Generados
#+begin_src php :tangle gpg.php
.
,*/
#+end_src
* Temas
- Cuento presentación de Alice Bob
- Mostrar un ROT por 5 segs. que Pablo lo copie y lo decifre.
- Explicar que eso se usaba y que sirvió, pero si otros lo copian no sirve.
- Breve reseña histórica: criptografía clásica vs moderna.
- Mostrar Wireshark y acceso a una página sin SSL/TLS. Aplicaciones.
* Python
** gnupg o pretty_bad_protocol Package
El paquete ~gnupg~ provée la clase GPG que puede generar claves y recibirlas del servidor de gnupg.net.
Es mantenido por isislovecruft y el código fuente está disponible en [[https://github.com/isislovecruft/python-gnupg][su repositorio en GitHub]].
Se puede instalar usando ~pip3 install --user pretty-bad-protocol~ o ~pip3 install --user gnupg~ para versiones legacy.
Éste paquete no utiliza las claves del sistema. En cambio, guarda las claves en otro directorio al del comando de terminal GPG.
*** Importar una Clave Pública
Para importar e inicializar una instancia GPG se ejecuta lo siguiente.
#+begin_src python :tangle gnupgEj2.py :session gpg
from pretty_bad_protocol.gnupg import GPG
gpg = GPG()
#+end_src
#+RESULTS:
*** Recibir Claves
Con este comando se recibe una clave pública con el ID ~C936B214EB93830D~.
#+begin_src python :tangle gnupgEj2.py :session gpg
a = gpg.recv_keys('hkp://keys.gnupg.net', '8EA85F43420045020C30EC02C936B214EB93830D')
a.counts
#+end_src
#+RESULTS:
: OrderedDict([('count', 1), ('no_user_id', 0), ('imported', 0), ('imported_rsa', 0), ('unchanged', 1), ('n_uids', 0), ('n_subk', 0), ('n_sigs', 0), ('n_revoc', 0), ('sec_read', 0), ('sec_imported', 0), ('sec_dups', 0), ('not_imported', 0)])
*** Crear Claves
Los datos del par de claves se genera con el siguiente comando.
#+BEGIN_SRC python :session gpg :tangle gnupgEj2.py
key_settings = gpg.gen_key_input(key_type='RSA',
key_length=1024,
passphrase='foo')
key_settings
#+END_SRC
#+RESULTS:
: Key-Type: RSA
: Key-Length: 1024
: Name-Real: Autogenerated Key
: Expire-Date: 2019-09-14
: Name-Email: user@host
: Passphrase: foo
: %commit
Con el siguiente comando se genera el par de claves con los datos de ~key_settings~.
#+BEGIN_SRC python :session gpg :tangle gnupgEj2.py
key = gpg.gen_key(key_settings)
key
#+END_SRC
#+RESULTS:
: A4F5AC2E416DAACF64921300E56BBABB474F92E5
*** Cifrar
#+BEGIN_SRC python :session gpg :tangle gnupgEj2.py
message = "The crow flies at midnight."
encrypted = gpg.encrypt(message, key.fingerprint, passphrase='foo')
str(encrypted)
#+END_SRC
#+RESULTS:
: -----BEGIN PGP MESSAGE-----
:
: hIwD5Wu6u0dPkuUBBACi56QCmg2cbrWceNpJvncSWmNnO8JmSHcrOxN2RCPaklLr
: BiSHq20hZJn+GxVK3LZvq+3VccSANBFxHGnYszatAMl11vNMz3QCvubFCmi8ou6h
: NxMFTKL4kKW5lypxFDnTaVDDLLUyLdz1rNzF9Ee56KQ9DeBD9B0h/pI/qWRcgdJW
: AZdIpxR3/gtNeKmWGx9h1Uo6TG546VqkWky2FYwc9LHwHrmGg/HCdTXCq0LULkDY
: oVOXuhCjxjD8FlMaoh4wsN27GPn8pqoZ5H81Huuu5m7chq04DYA=
: =KL3J
: -----END PGP MESSAGE-----
*** Descifrar
#+BEGIN_SRC python :session gpg :tangle gnupgEj2.py
decrypted = gpg.decrypt(str(encrypted), passphrase='foo', always_trust=True)
str(decrypted)
#+END_SRC
#+RESULTS:
** GPG Package
El paquete ~gpg~ es mantenido por gnupg.org. Utiliza las claves que ya están en el sistema, por lo que se puede utilizar el comando de terminal ~gpg2~ o Kleopatra para gestionar las claves.
Se puede instalar utilizando ~pip3 install --user gpg~.
#+BEGIN_SRC python :session gpg :tangle gpgEj1.py
import gpg
c = gpg.Context(armor=True)
c
#+END_SRC
#+RESULTS:
:
*** Listar Claves
Para listar las claves públicas generadas o importadas.
#+BEGIN_SRC python :session gpg :tangle gpgEj1.py
g = c.keylist('devfest2018')
ks = []
for i in g:
ks.append(i)
#+END_SRC
#+RESULTS:
*** Cifrar
#+BEGIN_SRC python :session gpg :results example :tangle gpgEj1.py
enc = c.encrypt('hola mundo'.encode(), recipients=ks, sign=False)
str(enc[0])
#+END_SRC
#+RESULTS:
: b'-----BEGIN PGP MESSAGE-----\n\nhQEMA7b6mxGe2IL+AQf/e35V0Dxg/LoaV7WRYQuk055ng9tBNalBEnEELsyJPxQ2\n+Cdf9oW5QaGpm5iUZ54eP5vGoL5D5UQY829keohiaUfLmxojPpcHitx1HgDbJEVB\nAeIQL1OK08D6xa+6Pj6HzvNMlu6kiTWs1dmwAOJxX8qFPVEAsybIwYTUjMYvRKPQ\nvNai/VpZNvZFqUxiJsggn+1qsMTUKpsABvj90emWjk5NOl2C1cFQwpcsyIevM2EN\nyYSDHjQ3EI3uUdoi9GU01QqK6+LakOJ3NuzCzE55u0036Ic37z6s5pg2hcDdUAF/\ngNIhSappcLeiQQGyxWofigRjhC7LsLzdC1JXPPIr5dJFATHrl4QkwsgaqbfhqABb\nfW7nc59Sn4D6NgQiBiywklyDG7tDlu1rcn3azYMAG1ShmTRmOKHSmJFVlCeK8BPK\n8SOphDIO\n=d1Ub\n-----END PGP MESSAGE-----\n'
*** Descifrar
#+BEGIN_SRC python :session gpg :results example :tangle gpgEj1.py
dec = c.decrypt(enc[0])
dec[0]
#+END_SRC
#+RESULTS:
: b'hola mundo'
* Ruby
La gema ~gpgme~ provee una interfaz para gestionar las claves de GPG que utiliza el sistema.
Se puede instalar por medio de ~gem install gpgme~.
#+BEGIN_SRC ruby :session gpgruby :tangle gpgme.rb
require 'gpgme'
c = GPGME::Crypto.new :armor => true
#+END_SRC
#+RESULTS:
: #true}>
** Cifrar
#+BEGIN_SRC ruby :session gpgruby :tangle gpgme.rb
d = c.encrypt "hola mundo", :recipients => ['devfest2018']
d.to_s
#+END_SRC
#+RESULTS:
#+begin_example
-----BEGIN PGP MESSAGE-----
hQEMA7b6mxGe2IL+AQgAk5kXcB8NXPqSxLtLoFHmuZAunZZZCNNpnRmCJNj92lrW
51kSZVbT+Q2Fh2p1e+G29tqnIEx2prQJTp5ZzZJ8sdO0rBAujPRaq2bMd1CI+ICP
Xo3luq6y+eoV9KyWPsuOEhCnHbBy/MCM0EEvrVOBfyg8JxvnzoncTiZ4YW1FrMMJ
64wwNlg5M28GRSgnddXdlBePcN7plm8cv6BBsm0+458graiWtw7dWbs3yrcG9tLj
SYLmkmrX6PTnTKaeP/X0pg2PYkCAqlLJ498QePookBoZIL+2Zn6ikVIHsVNWvzgC
ezl2deNGiQL67myACPkU2XaJpEvuqAX8YBqgJrcwctJFAVzFGNKBmXQfD5iiszOY
XqitbcFcAkGEqOcVW5JS5/OQCJCotSWUw2jgG4EZmq6lu07WZMa/es6hnAdJ5lx8
9hQ8n9j9
=RY4u
-----END PGP MESSAGE-----
#+end_example
** Descifrar
#+BEGIN_SRC ruby :session gpgruby :tangle gpgme.rb
d2 = c.decrypt d.to_s
d2.to_s
#+END_SRC
#+RESULTS:
: hola mundo
* PHP
La librería estándar posee un paquete llamado ~gpg~. Se puede utilizar para gestionar las claves que GPG posee en el sistema.
Se instala utilizando el gestor de paquetes propia de la distribución GNU/Linux que se está utilizando. También se puede utilizad PECL: ~pecl install gpg~.
Para empezar a usarlo, se requiere crear un contexto.
#+begin_src php :tangle gpg.php
$res = gnupg_init();
#+end_src
** Cifrar
Primero, se debe indicar cuáles claves usar para cifrar con la función ~gnupg_addencryptkey()~ y para firmar digitalmente con ~gnupg_addsignkey()~.
#+BEGIN_SRC php :tangle gpg.php
gnupg_addencryptkey($res, "christian.gimenez@fi.uncoma.edu.ar");
gnupg_addsignkey($res, "christian.gimenez@fi.uncoma.edu.ar");
$cipher = gnupg_encryptsign($res, 'Hello World');
#+END_SRC
** Descifrar
Para descifrar, se requiere de una variable donde se guarda el contenido. La función ~gnupg_decryptverify()~ guarda el resultado en ~$plaintext~ y devuelve en ~$info~ información del estado.
#+BEGIN_SRC php :tangle gpg.php
$plaintext = "";
$info = gnupg_decryptverify($res, $cipher, $plaintext);
var_dump($plaintext)
print_r($info);
#+END_SRC
* Meta :noexport:
# ----------------------------------------------------------------------------------------------------
#+AUTHOR: Gimenez, Christian
#+DATE: 15 sep 2018
#+EMAIL:
#+TITLE: Introducción a la Criptografía
#+SUBTITLE: GDG-DevFest 2018
#+DESCRIPTION:
#+KEYWORDS:
#+LANGUAGE: es
#+STARTUP: inlineimages hidestars content hideblocks entitiespretty indent fninline latexpreview
#+TODO: TODO(t!) CURRENT(c!) PAUSED(p!) | DONE(d!) CANCELED(C!@)
#+OPTIONS: H:3 num:t toc:t \n:nil @:t ::t |:t ^:{} -:t f:t *:t <:t
#+OPTIONS: TeX:t LaTeX:t skip:nil d:nil todo:t pri:nil tags:not-in-toc tex:imagemagick
#+INFOJS_OPT: view:nil toc:nil ltoc:t mouse:underline buttons:0 path:~/emacs_stuff/dists/scripts/org-info.js
#+EXPORT_SELECT_TAGS: export
#+EXPORT_EXCLUDE_TAGS: noexport
#+LINK_UP:
#+LINK_HOME:
#+XSLT:
# Local Variables:
# org-hide-emphasis-markers: t
# org-use-sub-superscripts: "{}"
# fill-column: 80
# End: