IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau C Discussion :

récupération clé publique rsa dans un certificat


Sujet :

Réseau C

  1. #1
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut récupération clé publique rsa dans un certificat
    Bonjour!

    j'ai un serveur et un client qui ont chacun un certificat et une clé privée rsa associée. Or, je voudrais faire des échanges de données chiffrées entre eux avec RSA. Actuellement, je génère des nouvelles paires de clés (privées/publiques) rsa, j'échange les clés publiques et je chiffre.
    Mais, je voudrais éviter ça et utiliser directement la clé publique contenue dans le certificat et la clé privée associée.
    Mon problème est que je ne parviens pas à lire la clé publique contenue dans le certificat...
    Sauriez vous s'il existe une fonction que je puisse utiliser ou une méthode à utiliser pour y arriver...?

    merci par avance pour vos réponses

  2. #2
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Par défaut
    Quel est le format actuel de ton certificat, il est visible avec la mmc (donc dans la base de registres), c'est un fichier (p12, pfx, pkcs) ?

    Sous quel format tu veux la clé publique, quel programme utilise cette clé publique (et surtout comment ?).

    Est ce que la manipulation/exportation, tu veux la faire 1 seule fois (et donc un export manuel va très bien) ou bien tu veux le faire par programme (et donc tu veux des points d'entrée de la cryptoAPI, il faut aussi connaitre l'OS pour cela).

    Voilà, je t'ai battu , tu poses une question et je te réponds par 3 questions
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  3. #3
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    bonjour

    alors...

    1)le certificat est au format PEM (mmc??? késaco??)

    2)en fait... je sais pas trop... disons que si quand je recoi le certificat, j'arrive à attraper la clé publique et à la mettre dans un fichier PEM ca peut etre pas mal... parce que après j'utilise l'algo rsa pour chiffré et envoyé ma clé symétrique

    3) je suis sous linux ^^
    1 seule fois ou plusieurs fois... ben à priori, qu'une seule fois je pense...

    et du coup... il faudrai que je positionne mon curseur la ou la clé publique commence dans mon certificat et que je copie ca dans un fichier PEM... mais comment faire pour 1)trouver ou positionner le curseur ; 2)faire en sorte que ca soit le fichier PEM créé soit valide... c'est pas un peu usine à gaz mon idée...?

  4. #4
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Par défaut
    MMC est la console de management Microsoft qui permet (entres autres) de gérer les certificats. Tu es sur Linux, donc tu n'es pas directement concerné.

    Dans ton cas, la solution s'appelle openssl. C'est un programme qui se comporte comme un shell mais qui permet de faire toutes les manipulations que tu veux (et même d'autres ) autour de la cryptographie dont : "extraction de la clé publique d'un certificat".

    openssl est un programme très très complet qui possède une foultitude d'options et de commandes. Donc google est ton ami, je ne sais pas t'aider plus mais je sais que c'est faisable.
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  5. #5
    Membre Expert Avatar de nicolas.sitbon
    Profil pro
    Inscrit en
    Août 2007
    Messages
    2 015
    Détails du profil
    Informations personnelles :
    Âge : 42
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 2 015
    Par défaut
    Il y a une fonction openssl qui le fait très bien si tu veux : PEM_read_RSAPublicKey().
    Cordialement.

  6. #6
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Par défaut
    Une remarque à laquelle je viens de penser.

    Le certificat que tu as, possède une politique d'utilisation de la clé publique (date d'expiration, fonctionnalités d'usage de la clé, ...). En extrayant la clé publique de son enveloppe (le certificat), tu vas perdre ces informations et tu risques de détourner cette politique. Par exemple, tu peux te retrouver à utiliser cette clé publique alors que le certificat dit que la clé est expirée.

    J'espère que je me suis bien fait comprendre.
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  7. #7
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    il me semblait que j'avais déja essayé avec cette fonction (parce que je l'utilise après quand je génère moi meme mes clés...) et ca ne marche pas...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
          /*ouverture du fichier*/
          if((fp = fopen(CLE_PUB_SERV,"r")) == NULL) 
              {
              perror("Public key doesn't exist\n");
              exit(EXIT_FAILURE);
              }
          /*lecture de la clé publique*/
          if((key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL)) == NULL) 
             {
             perror("problems while reading Public Key.\n");
             exit(EXIT_FAILURE);
             }
          /*fermeture du fichier*/
          fclose(fp);
          /*retourne la valeur de la clé lue*/
          return key;
    et il me met :
    problems while reading Public Key.
    : Success
    ce qui me laisse perplexe...


    [pour les histoires de certificats, quand je fais ma connexion SSL, je les vérifie, la validité notamment]

  8. #8
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Par défaut
    Est ce que tu peux mettre ton certificat en attachement (Rappel : un certificat est public donc il n'y a aucune contre indication à la diffuser SAUF s'il contient la clé privée)
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  9. #9
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut

    voila :
    Certificate:
    Data:
    Version: 3 (0x2)
    Serial Number: 1 (0x1)
    Signature Algorithm: sha1WithRSAEncryption
    Issuer: C=FR, ST=france, L=paris, O=idf, OU=fr, CN=10.102.13.114
    Validity
    Not Before: Sep 9 14:11:19 2008 GMT
    Not After : Sep 9 14:11:19 2009 GMT
    Subject: C=FR, ST=france, L=paris, O=idf, OU=fr, CN=10.102.13.114
    Subject Public Key Info:
    Public Key Algorithm: rsaEncryption
    RSA Public Key: (512 bit)
    Modulus (512 bit):
    00:b2:a7:65:c4:8b:44:33:4d:5e:e3:af:ae:12:0c:
    e4:59:30:b9:49:7d:2f:6f:15:47:9f:86:21:8e:f4:
    af:1e:12:2e:0b:72:08:dc:60:93:e9:4a:9e:e0:93:
    c6:78:47:fe:e4:c9:94:2d:53:83:e9:56:9d:2b:76:
    87:de:00:4d:0d
    Exponent: 65537 (0x10001)
    X509v3 extensions:
    Netscape Comment:
    Certificat Serveur SSL
    X509v3 Subject Key Identifier:
    55:27:28:F9:F3:BF:A3:02:95:30:35:C2:FB:5A:8C:48:7A:24:7F:8C
    X509v3 Authority Key Identifier:
    keyid:B0:40:42:0B:AB:1C:B3:C9:2C:7E:75:1D:76:FA:27:94:58:31:22:0E
    DirName:/C=FR/ST=france/L=paris/O=idf/OU=fr/CN=10.102.13.114
    serial:01

    X509v3 Issuer Alternative Name:
    <EMPTY>

    X509v3 Subject Alternative Name:
    DNS:www.webserver.com, DNS:www.webserver-bis.com
    X509v3 Basic Constraints: critical
    CA:FALSE
    X509v3 Key Usage:
    Digital Signature, Non Repudiation, Key Encipherment
    Netscape Cert Type:
    SSL Server
    X509v3 Extended Key Usage:
    TLS Web Server Authentication
    Signature Algorithm: sha1WithRSAEncryption
    4f:9c:bc:44:03:02:bb:b9:4c:e1:01:03:1d:c9:00:47:60:51:
    2d:28:84:51:a0:7b:22:17:20:7b:c4:3d:25:df:fa:46:30:15:
    9b69:8d:ab:2c:34:96:5a:4a:9b:5f:cd:54:d4:ab:19:13:
    c3:6e:5d:70:1a:a7:e6:52:25:eb
    -----BEGIN CERTIFICATE-----
    MIIDGTCCAsOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJGUjEP
    MA0GA1UECBMGZnJhbmNlMQ4wDAYDVQQHEwVwYXJpczEPMA0GA1UEChMGYWFzdHJh
    MQswCQYDVQQLEwJmcjEWMBQGA1UEAxMNMTAuMTAyLjEzLjExNDAeFw0wODA5MDkx
    NDExMTlaFw0wOTA5MDkxNDExMTlaMGQxCzAJBgNVBAYTAkZSMQ8wDQYDVQQIEwZm
    cmFuY2UxDjAMBgNVBAcTBXBhcmlzMQ8wDQYDVQQKEwZhYXN0cmExCzAJBgNVBAsT
    AmZyMRYwFAYDVQQDEw0xMC4xMDIuMTMuMTE0MFwwDQYJKoZIhvcNAQEBBQADSwAw
    SAJBALKnZcSLRDNNXuOvrhIM5FkwuUl9L28VR5+GIY70rx4SLgtyCNxgk+lKnuCT
    xnhH/uTJlC1Tg+lWnSt2h94ATQ0CAwEAAaOCAV4wggFaMCUGCWCGSAGG+EIBDQQY
    FhZDZXJ0aWZpY2F0IFNlcnZldXIgU1NMMB0GA1UdDgQWBBRVJyj587+jApUwNcL7
    WoxIeiR/jDCBjgYDVR0jBIGGMIGDgBSwQEILqxyzySx+dR12+ieUWDEiDqFopGYw
    ZDELMAkGA1UEBhMCRlIxDzANBgNVBAgTBmZyYW5jZTEOMAwGA1UEBxMFcGFyaXMx
    DzANBgNVBAoTBmFhc3RyYTELMAkGA1UECxMCZnIxFjAUBgNVBAMTDTEwLjEwMi4x
    My4xMTSCAQEwCQYDVR0SBAIwADAzBgNVHREELDAqghF3d3cud2Vic2VydmVyLmNv
    bYIVd3d3LndlYnNlcnZlci1iaXMuY29tMAwGA1UdEwEB/wQCMAAwCwYDVR0PBAQD
    AgXgMBEGCWCGSAGG+EIBAQQEAwIGQDATBgNVHSUEDDAKBggrBgEFBQcDATANBgkq
    hkiG9w0BAQUFAANBAE+cvEQDAru5TOEBAx3JAEdgUS0ohFGgeyIXIHvEPSXf+kYw
    FZvxaY2rLDSWWkqbX81U1KsZE8NuXXAap+ZSJes=
    -----END CERTIFICATE-----

  10. #10
    Rédacteur

    Avatar de ram-0000
    Homme Profil pro
    Consultant en sécurité
    Inscrit en
    Mai 2007
    Messages
    11 517
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Consultant en sécurité
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mai 2007
    Messages : 11 517
    Par défaut
    Ce que j'ai fait

    1/ ecrire le certificat dans un fichier texte cert.txt
    Code fichier cert.txt : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    -----BEGIN CERTIFICATE-----
    MIIDGTCCAsOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJGUjEP
    MA0GA1UECBMGZnJhbmNlMQ4wDAYDVQQHEwVwYXJpczEPMA0GA1UEChMGYWFzdHJh
    MQswCQYDVQQLEwJmcjEWMBQGA1UEAxMNMTAuMTAyLjEzLjExNDAeFw0wODA5MDkx
    NDExMTlaFw0wOTA5MDkxNDExMTlaMGQxCzAJBgNVBAYTAkZSMQ8wDQYDVQQIEwZm
    cmFuY2UxDjAMBgNVBAcTBXBhcmlzMQ8wDQYDVQQKEwZhYXN0cmExCzAJBgNVBAsT
    AmZyMRYwFAYDVQQDEw0xMC4xMDIuMTMuMTE0MFwwDQYJKoZIhvcNAQEBBQADSwAw
    SAJBALKnZcSLRDNNXuOvrhIM5FkwuUl9L28VR5+GIY70rx4SLgtyCNxgk+lKnuCT
    xnhH/uTJlC1Tg+lWnSt2h94ATQ0CAwEAAaOCAV4wggFaMCUGCWCGSAGG+EIBDQQY
    FhZDZXJ0aWZpY2F0IFNlcnZldXIgU1NMMB0GA1UdDgQWBBRVJyj587+jApUwNcL7
    WoxIeiR/jDCBjgYDVR0jBIGGMIGDgBSwQEILqxyzySx+dR12+ieUWDEiDqFopGYw
    ZDELMAkGA1UEBhMCRlIxDzANBgNVBAgTBmZyYW5jZTEOMAwGA1UEBxMFcGFyaXMx
    DzANBgNVBAoTBmFhc3RyYTELMAkGA1UECxMCZnIxFjAUBgNVBAMTDTEwLjEwMi4x
    My4xMTSCAQEwCQYDVR0SBAIwADAzBgNVHREELDAqghF3d3cud2Vic2VydmVyLmNv
    bYIVd3d3LndlYnNlcnZlci1iaXMuY29tMAwGA1UdEwEB/wQCMAAwCwYDVR0PBAQD
    AgXgMBEGCWCGSAGG+EIBAQQEAwIGQDATBgNVHSUEDDAKBggrBgEFBQcDATANBgkq
    hkiG9w0BAQUFAANBAE+cvEQDAru5TOEBAx3JAEdgUS0ohFGgeyIXIHvEPSXf+kYw
    FZvxaY2rLDSWWkqbX81U1KsZE8NuXXAap+ZSJes=
    -----END CERTIFICATE-----
    2/ extraire la clé publique
    Code commande : Sélectionner tout - Visualiser dans une fenêtre à part
    openssl x509 -in cert.txt -pubkey -noout > pub.txt

    3/ affichage du fichier pub.txt
    Code fichier pub.txt : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    -----BEGIN PUBLIC KEY-----
    MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALKnZcSLRDNNXuOvrhIM5FkwuUl9L28V
    R5+GIY70rx4SLgtyCNxgk+lKnuCTxnhH/uTJlC1Tg+lWnSt2h94ATQ0CAwEAAQ==
    -----END PUBLIC KEY-----
    Raymond
    Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

    Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
    e-verbe Un logiciel de conjugaison des verbes de la langue française.

    Ma page personnelle sur DVP
    .

  11. #11
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    ok... est ce qu'il y aurai un équivalent en fonction à la ligne de commande que tu as utilisé...??
    parce que je vois pas trop comment je peux faire ca au milieu des échanges entre mes deux appli client/serveur...
    mais la solution peut etre de faire ca avant de lancer les applis... faut réfléchir...

  12. #12
    Membre Expert Avatar de nicolas.sitbon
    Profil pro
    Inscrit en
    Août 2007
    Messages
    2 015
    Détails du profil
    Informations personnelles :
    Âge : 42
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 2 015
    Par défaut
    Citation Envoyé par Bathou Voir le message
    il me semblait que j'avais déja essayé avec cette fonction (parce que je l'utilise après quand je génère moi meme mes clés...) et ca ne marche pas...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
          /*ouverture du fichier*/
          if((fp = fopen(CLE_PUB_SERV,"r")) == NULL) 
              {
              perror("Public key doesn't exist\n");
              exit(EXIT_FAILURE);
              }
          /*lecture de la clé publique*/
          if((key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL)) == NULL) 
             {
             perror("problems while reading Public Key.\n");
             exit(EXIT_FAILURE);
             }
          /*fermeture du fichier*/
          fclose(fp);
          /*retourne la valeur de la clé lue*/
          return key;
    et il me met :
    ce qui me laisse perplexe...


    [pour les histoires de certificats, quand je fais ma connexion SSL, je les vérifie, la validité notamment]
    commence par lire le man de openssl

  13. #13
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    j'ai déja pas mal potassé sur openssl et niveau documentation, c'est malheureusement souvent incomplet...
    openssl en ligne de commande, on trouve beaucoup de choses mais pour faire la meme chose en codant, ben pas évident... surtout qu'il y a plein de fonctions, et que mon niveau d'anglais est pas des meilleurs...

    mais bon... pour le moment, je vais rester comme j'étais en recréeant un jeu de clé privé/publique. sauf si j'ai une illumination... ou si quelq'un en a une...

    merci pour vos réponses...

  14. #14
    Membre Expert Avatar de nicolas.sitbon
    Profil pro
    Inscrit en
    Août 2007
    Messages
    2 015
    Détails du profil
    Informations personnelles :
    Âge : 42
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 2 015
    Par défaut
    montre un exemple de code compilable, après je ferais les corrections s'il y a besoin.
    Cordialement.

  15. #15
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    Bonjour!
    merci de ta proposition ^^
    actuellement mon code ressemble à ça... :
    client_SSL.c :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    /*CLIENT*/
     
    #include "client_SSL.h"
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			Fonction Principale			//
    //								//
    //////////////////////////////////////////////////////////////////
    int main()
    {          
    int     err; 
     
     
     
    int     verify_client = ON; /* To not verify a client certificate, set OFF */   
    int     sock;         
    struct sockaddr_in server_addr;     
    char  *str;       
    char    buf [100];         
    char    hello[80]; 
     
     
    SSL_CTX         *ctx;       
    SSL            *ssl;       
    SSL_METHOD      *meth;      
    X509            *server_cert;        
    EVP_PKEY        *pkey; 
     
     
    short int       s_port = 563;      
    const char      *s_ipaddr = "10.102.13.114";      
     
    FILE*fp_recu,*fp_enc,*fpin=NULL,*fpout=NULL,*fp,*fp_cle, *fp_emis;
    int longueur=0;
     
    int n=0,recp_fich;  
    unsigned char *cipher=NULL,*plain=NULL;
    int size=0,len=0,ks=0;
    RSA *key=NULL;
    long taille_fichier;
     
     
    int flags1 = 0, flags2 = 0, outfd, infd, decfd;
      mode_t mode;
    	bzero (&mode, sizeof (mode));
     
    	flags1 = flags1 | O_RDONLY;
    	flags2 = flags2 | O_RDONLY;
    	flags2 = flags2 | O_WRONLY;
    	flags2 = flags2 | O_CREAT;
     
    	mode = mode | S_IRUSR;
    	mode = mode | S_IWUSR;
     
     
      ////////////////////////////////////////////////////////////////
      /*GENERATION DE LA CLE SYMETRIQUE*/
     
      /*génère la clé*/
      generate_key ();
      printf("the key is generate\n\n");
     
      /*ouverture du fichier*/
      fp_cle=fopen(FICHIER_CLE_SYMETRIQUE,"w");
      if (fp_cle==NULL)
            {
            perror("call to open\n");
            exit(1);
            }
     
     
      fwrite(key2,sizeof(*key2),16,fp_cle);
     
      fwrite(iv,sizeof(*iv),8,fp_cle);
      /*fermeture du fichier*/
      fclose(fp_cle);
     
     
      ////////////////////////////////////////////////////////////////
      /*INITIALIZATION*/
     
      /*message to send*/
      printf ("Message to be sent to the SSL server: ");          
      fgets (hello, 80, stdin);       
     
      /* Load encryption & hashing algorithms for the SSL program */  
      SSL_library_init();     
     
      /* Load the error strings for SSL & CRYPTO APIs */      
      SSL_load_error_strings();      
     
      /* Create an SSL_METHOD structure (choose an SSL/TLS protocol version) */   
      meth = SSLv3_method();  
     
     
      /* Create an SSL_CTX structure */   
      ctx = SSL_CTX_new(meth);                                
      RETURN_NULL(ctx);   
     
     
      ////////////////////////////////////////////////////////////////  
      /*VERIFICATION*/
     
      if(verify_client == ON)         
          {               
          /* Load the client certificate into the SSL_CTX structure */               
          if (SSL_CTX_use_certificate_file(ctx, RSA_CLIENT_CERT,       SSL_FILETYPE_PEM) <= 0) 
              {                   
              ERR_print_errors_fp(stderr);                        
              exit(1);            
              }               
     
          /* Load the private-key corresponding to the client certificate */          
          if (SSL_CTX_use_PrivateKey_file(ctx, RSA_CLIENT_KEY,SSL_FILETYPE_PEM) <= 0) 
              {                     
              ERR_print_errors_fp(stderr);                        
              exit(1);            
              }               
     
          /* Check if the client certificate and private-key matches */               
          if (!SSL_CTX_check_private_key(ctx)) 
              {                      
              fprintf(stderr,"Private key does not match the certificate public key\n");                    
              exit(1);            
              }   printf("Checking certificate and private key...\n");
          }       
     
     
      /* Load the RSA CA certificate into the SSL_CTX structure */        
      /* This will allow this client to verify the server's     */        
      /* certificate.                                           */ 
     
     
      if (!SSL_CTX_load_verify_locations(ctx, RSA_CLIENT_CA_CERT, NULL)) 
          {                
          ERR_print_errors_fp(stderr);                
          exit(1);    
          }         
     
      /* Set flag in context to require peer (server) certificate */        
      /* verification */         /*
      SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);         
      SSL_CTX_set_verify_depth(ctx,1);*/       
      printf("VERIFICATION OK!\n");
     
     
     
      ////////////////////////////////////////////////////////////////
      /*SOCKET*/        
     
      /* Set up a TCP socket */       
      sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);              
      RETURN_ERR(sock, "socket");     
      memset (&server_addr, '\0', sizeof(server_addr));       
      server_addr.sin_family = AF_INET;  
      server_addr.sin_port = htons(s_port);       
     
      /* Server Port number */     
      server_addr.sin_addr.s_addr = inet_addr(s_ipaddr); 
     
      /* Server IP */      
     
      /* Establish a TCP/IP connection to the SSL client */           
      err = connect(sock, (struct sockaddr*) &server_addr, sizeof(server_addr));          
      RETURN_ERR(err, "connect");         
      printf("\n\n");
     
     
     
      ////////////////////////////////////////////////////////////////
      /*SSL*/
     
      /* An SSL structure is created */       
      ssl = SSL_new (ctx);    
      RETURN_NULL(ssl);       
     
      /* Assign the socket into the SSL structure (SSL and socket without BIO) */         
      SSL_set_fd(ssl, sock);  
     
      /* Perform SSL Handshake on the SSL client */       
      err = SSL_connect(ssl);         
      RETURN_SSL(err);        
     
      /* Informational output (optional) */       
      printf ("SSL connection using %s\n", SSL_get_cipher (ssl));     printf("\n\n");
     
      /* Get the server's certificate (optional) */       
      server_cert = SSL_get_peer_certificate (ssl);           
      if (server_cert != NULL)       
          {               
          printf ("Server certificate:\n"); 
          str = X509_NAME_oneline(X509_get_subject_name(server_cert),0,0);            
          RETURN_NULL(str);           
          printf ("\t subject: %s\n", str);           
          free (str);             
          str = X509_NAME_oneline(X509_get_issuer_name(server_cert),0,0);             
          RETURN_NULL(str);           
          printf ("\t issuer: %s\n", str);            
          free(str);              
          X509_free (server_cert); 
          }        
      else                
          printf("The SSL server does not have certificate.\n");     
     
      printf("\n\n");
     
      ////////////////////////////////////////////////////////////////
      /*-------- DATA EXCHANGE - send message and receive reply. -------*/        
      printf("\n************************************");
      printf("\nDATA EXCHANGE\n");
     
      /* Send data to the SSL server */   
      err = SSL_write(ssl, hello, strlen(hello));     
      RETURN_SSL(err);     
     
      /* Receive data from the SSL server */      
      err = SSL_read(ssl, buf, sizeof(buf)-1);                        
      RETURN_SSL(err);    
      buf[err] = '\0';   
      printf ("Received %d chars:'%s'\n\n", err, buf);         
     
      ////////////////////////////////////////////////////////////////
      /*RECEPTION DE LA CLE PUBLIQUE*/
     
      /*ouverture du fichier*/
      fp_recu=fopen(CLE_PUB_SERV,"wb");
      if (fp_recu==NULL)
          {
          perror("call to open\n");
          exit(1);
          }
     
      /*reception de la taille du fichier*/
      int recp_taille=SSL_read(ssl,&taille_fichier,sizeof(taille_fichier)); 
      if (recp_taille==-1)
          {
          perror("call to rcv taille\n");
          exit(1);
          } 
      taille_fichier=ntohl(taille_fichier); 
      printf("Public Key size %d receive\n",taille_fichier);
      printf("Reception...\n");
     
      /*tant que l'on a pas tout reçu*/
     
      while (taille_fichier > 0 && (recp_fich = SSL_read(ssl, buf, sizeof (buf))) > 0)
          {
          /*on recoi*/
          if(recp_fich <0)
              {
              perror("call to rcv\n");
              exit(1);
              }
     
          /*on écrit dans le fichier*/
          fwrite(buf,1,recp_fich,fp_recu);
     
          /*on diminue la taille*/
          taille_fichier -= recp_fich;
     
          /*RAZ du buffer*/
          memset(&buf,0,sizeof(buf));
          }
     
      /*fermeture du fichier*/
      fclose(fp_recu);
      printf("Reception Public Key Done...\n\n");
      ////////////////////////////////////////////////////////////////
      /*CHIFFREMENT DU FICHIER CLE SYMETRIQUE*/
     
      /*lecture de la clé publique*/
      key = readpemkeys(READPUB);
     
      /*ouverture du fichier input*/
      if(!(fpin = fopen(FICHIER_CLE_SYMETRIQUE, "rb"))) 
          {
          fprintf(stderr, "Error: Cannot locate input file.\n");
          exit(EXIT_FAILURE);
          }
     
      /*ouverture du fichier output*/
      fpout = fopen(FICHIER_CLE_SYMETRIQUE_ENC, "wb");
     
      /*taille de la clé*/
      ks = RSA_size(key);
     
      /*allocation ed mémoire*/
      plain = (unsigned char *)malloc(ks * sizeof(unsigned char));
      cipher = (unsigned char*)malloc(ks * sizeof(unsigned char));
      printf("Encrypting '%s' file.\n",FICHIER_CLE_SYMETRIQUE);
     
      /*tant qu'on a pas atteint la fin du fichier input*/
      while(!feof(fpin)) 
          {
          /*remise à zéro de plain et cipher*/
          memset(plain,'\0',ks + 1);
          memset(cipher, '\0', ks + 1);
     
          /*lecture dans le fichier input*/
          len = fread(plain, 1, ks - 11, fpin);
     
          /*chiffrement avec Rsa*/
          size = rsa_encrypt(key, plain, len, &cipher);
     
          /*écriture dans le fichier d'arrivée*/
          fwrite(cipher, 1, size, fpout);
     
          }
     
      /*fermeture des deux fichiers*/
      fclose(fpout);
      fclose(fpin);
     
      /*libération de la mémoire*/
      free(cipher);
      free(plain);
      RSA_free(key);
      printf("Encrypting Symetric Key Done.\n");
     
     
      ////////////////////////////////////////////////////////////////
      /*ENVOI DU-DIT FICHIER*/
     
      /*ouverture du fichier*/
      fp_enc=fopen(FICHIER_CLE_SYMETRIQUE_ENC,"rb");
      if (fp_enc==NULL)
          {
          perror("call to open\n");
          exit(1);
          }
     
      /*envoi de la taille du fichier*/
      long taille =fsize(fp_enc);
      taille=htonl(taille);
      longueur=sizeof(taille);
      int env_taille=SSL_write(ssl, &taille, longueur);
      if (env_taille==-1)
          {
          perror("call to send\n");
          exit(1);
          }
      printf("Send Encrypting Symetric Key ok\n");
     
     
      /*tant qu'on n'a pas tout envoyé, tant qu'on n'a pas atteint la fin du fichier*/
      fseek(fp_enc,0,SEEK_SET);
      while ((n = fread(buf, 1, sizeof(buf), fp_enc)) > 0)
          {
          /*on envoi*/
          int envoi=SSL_write(ssl, buf, n);
          if (envoi==-1)
              {
              perror("call to send\n");
              exit(1);
              }
          }
     
     
      /*fermeture du fichier*/
      fclose(fp_enc);
    printf("Sending Encrypting Symetric Key ok\n\n");
     
    /////////////////////////////////////////////////////////////////////
    printf("Encrypting File...\n");
    //chiffrement du fichier
     if ((infd = open (FICHIER_CLAIR, flags1, mode )) == -1)
        perror ("open input file error");
     
     if ((outfd = open (FICHIER_ENC, flags2, mode )) == -1)
        perror ("open output file error");
     encrypt (infd, outfd);
     close (infd);
     close (outfd);
     printf("the file is encrypt\n\n");
     
    //////////////////////////////////////////////////////////////////////
     
    printf("Sending File\n");
    /*ouverture du fichier*/
      fp_emis=fopen(FICHIER_ENC,"rb");
      if (fp_emis==NULL)
            {
            perror("call to open\n");
            exit(1);
            }
     
      /*envoi de la taille du fichier*/
     taille =fsize(fp_emis);
      longueur=sizeof(taille);
      env_taille=SSL_write(ssl, &taille, longueur);
      if (env_taille==-1)
            {
            perror("call to send\n");
            exit(1);
            }
          printf("envoi ok\n");
     
     
     
      /*tant qu'on n'a pas tout envoyé, tant qu'on n'a pas atteint la fin du fichier*/
      fseek(fp_emis,0,SEEK_SET);
    while ((n = fread(buf, 1, sizeof(buf), fp_emis)) > 0)
        {
     
        /*on envoi*/
        int envoi=SSL_write(ssl, buf, n);
        if (envoi==-1)
          {
          perror("call to send\n");
          exit(1);
          }
        }
     
     
     
      /*fermeture du fichier*/
      fclose(fp_emis);
     
     
     
     
     
    printf("Sending file ok!\n");
     
     
     
      printf("\nEND DATA EXCHANGE\n");
      printf("************************************\n");
     
     
      ////////////////////////////////////////////////////////////////
      /*--------------- SSL closure ---------------*/       
     
      /* Shutdown the client side of the SSL connection */         
      err = SSL_shutdown(ssl);        
      RETURN_SSL(err);         
     
      /* Terminate communication on a socket */        
      err = close(sock);         
      RETURN_ERR(err, "close");         
     
      /* Free the SSL structure */        
      SSL_free(ssl);         
     
      /* Free the SSL_CTX structure */        
      SSL_CTX_free(ctx);
     
      printf("Application terminate : good bye!\n");
     
    }
    client_SSL.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    /*Headers*/
    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    #include "errno.h"
    #include "netdb.h"
    #include "unistd.h"
    #ifdef __VMS
    #include "socket.h"
    #include "inet.h" 
    #include "in.h"
    #else
    #include "sys/types.h"
    #include "sys/socket.h"
    #include "netinet/in.h"
    #include "arpa/inet.h"
    #include "netdb.h"
    #include "fcntl.h"
    #include "sys/stat.h"
    #include "unistd.h"
    #endif 
     
    /*OpenSSL headers*/
    #include "openssl/crypto.h"
    #include "openssl/ssl.h"
     
    #include "openssl/bio.h"
     
    #include "openssl/err.h"
    #include "openssl/evp.h"
    #include "openssl/rsa.h"
    #include "openssl/des.h"
    #include "openssl/blowfish.h"
     
     
    #define RETURN_NULL(x) if ((x)==NULL) exit (1)
    #define RETURN_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
    #define RETURN_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(1); } 
     
     
     
    static int verify_callback(int ok, X509_STORE_CTX *ctx); 
     
    #define RSA_CLIENT_CERT       "client_ssl_cert.pem"
    #define RSA_CLIENT_KEY  "client_ssl_priv_key.key" 
    #define RSA_CLIENT_CA_CERT      "../cassl/cassl_cert.pem"
    #define RSA_CLIENT_CA_PATH      "bathou1" 
    #define ON      1
    #define OFF     0 
     
     
    #define READPUB 0
    #define READSEC 1
     
    int port = 563;
    unsigned char key2[16];
    unsigned char iv[8];
     
    /*fichiers PEM pour clés publiques/privées*/
    #define CLE_PRIVE "cle_privee.pem"
    #define CLE_PUBLIC "cle_publique.pem"
     
    #define CLE_PUB_SERV "cle_publique_serveur.pem"
    #define FICHIER_CLAIR "fichier_clair.txt"
    #define FICHIER_ENC "fichier_encode.bin"
     
    #define FICHIER_CLE_SYMETRIQUE "cle_symetrique.txt"
    #define FICHIER_CLE_SYMETRIQUE_ENC "cle_symetrique_enc.bin"
     
    #define IP_SIZE 1024
    #define OP_SIZE 1032
     
    void genkey(int size);
    int generate_key ();
     
    RSA* readpemkeys(int type);
    void genkey(int size);
    int rsa_encrypt(RSA *key, unsigned char *plain, int len, unsigned char **cipher);
    long fsize(FILE*fp);
    int generate_key ();
    int encrypt (int infd, int outfd);
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			read PEM keys function			//
    //								//
    //////////////////////////////////////////////////////////////////
    RSA* readpemkeys(int type)
     
    {
      FILE *fp;
      RSA *key=NULL;
     
      ////////////////////////////////////////////////////////////////
     
      /*si clé publique*/
      if(type == READPUB) 
          {
          /*ouverture du fichier*/
          if((fp = fopen(CLE_PUB_SERV,"r")) == NULL) 
              {
              fprintf(stderr,"Error: Public Key file doesn't exists.\n");
              exit(EXIT_FAILURE);
              }
          /*lecture de la clé publique*/
          if((key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL)) == NULL) 
             {
             fprintf(stderr,"Error: problems while reading Public Key.\n");
             exit(EXIT_FAILURE);
             }
          /*fermeture du fichier*/
          fclose(fp);
          /*retourne la valeur de la clé lue*/
          return key;
          }
     
      ////////////////////////////////////////////////////////////////
     
      /*si clé privée*/
    //  if(type == READSEC) 
    //    {
        /*ouverture du fichier*/
    //    if((fp = fopen(SECFILE,"r")) == NULL) 
    //      {
    //      fprintf(stderr,"Error: Private Key file doesn't exists.\n");
    //      exit(EXIT_FAILURE);
    //      }
        /*lecture de la clé privée*/
    //    if((key = PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL)) == NULL) 
    //      {
    //      fprintf(stderr,"Error: problmes while reading Private Key.\n");
    //      exit(EXIT_FAILURE);
    //      }
        /*fermeture du fichier*/
    //    fclose(fp);
        /*verification de la clé*/
        /*si =-1 échou*/
    //    if(RSA_check_key(key) == -1) 
    //      {
    //      fprintf(stderr,"Error: Problems while reading RSA Private Key in '%s' file.\n",SECFILE);
    //      exit(EXIT_FAILURE);
    //      } 
        /*si =0 échec*/
    //    else if(RSA_check_key(key) == 0) 
    //      {
    //      fprintf(stderr,"Error: Bad RSA Private Key readed in '%s' file.\n",SECFILE);
    //      exit(EXIT_FAILURE);
    //      }
    //    else/*on retourne la clé*/
    //      return key;
    //    }
      return key;
    }
     
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			GenerationKey fonction			//
    //								//
    //////////////////////////////////////////////////////////////////
    void genkey(int size)
    {
      RSA *key=NULL;
      FILE *fp;
     
      ////////////////////////////////////////////////////////////////
     
      /*génération de la clé*/
      if((key = RSA_generate_key(size,3,NULL,NULL)) == NULL) 
          {
          fprintf(stderr,"%s\n",ERR_error_string(ERR_get_error(),NULL));
          exit(EXIT_FAILURE);
          }
     
      /*vérification de la clé*/
      if(RSA_check_key(key) < 1) 
          {
          fprintf(stderr,"Error: Problems while generating RSA Key.\nRetry.\n");
          exit(EXIT_FAILURE);
          }
     
      ////////////////////////////////////////////////////////////////
     
      /*CLE PRIVEE*/
     
      /*ouverture du fichier de clé privée*/
      fp=fopen(CLE_PRIVE,"wb");
      /*écriture de la clé privée dans son fichier*/
      if(PEM_write_RSAPrivateKey(fp,key,NULL,NULL,0,0,NULL) == 0) 
          {
          fprintf(stderr,"Error: problems while writing RSA Private Key.\n");
          exit(EXIT_FAILURE);
          }
      /*fermeture du fichier*/
      fclose(fp);
     
     
     
      ////////////////////////////////////////////////////////////////
     
      /*CLE PUBLIQUE*/
     
      /*ouverture du fichier de clé publique*/
      fp=fopen(CLE_PUBLIC,"wb");
      /*écriture de la clé publique dans son fichier*/
      if(PEM_write_RSAPublicKey(fp,key) == 0) 
          {
          fprintf(stderr,"Error: problems while writing RSA Public Key.\n");
          exit(EXIT_FAILURE);
          }
      /*fermeture du fichier*/
      fclose(fp);
     
      ///////////////////////////////////////////////////////////////
     
      /*libération de la mémoire pour le contexte RSA*/
      RSA_free(key);
      return;
    }
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			RSA Encrypt Function			//
    //								//
    //////////////////////////////////////////////////////////////////
     
    int rsa_encrypt(RSA *key, unsigned char *plain, int len, unsigned char **cipher)
    {
      int clen=0;
      /*nombrea aléatoire*/
      srand(time(NULL));
      /*on chiffre*/
      if((clen = RSA_public_encrypt(len, plain, *cipher, key, RSA_PKCS1_PADDING)) == -1) 
        {
        fprintf(stderr, "%s\n", ERR_error_string(ERR_get_error(), NULL));
        exit(EXIT_FAILURE);
        } else
        return clen;
    }
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			fonction Fsize				//
    //								//
    //////////////////////////////////////////////////////////////////
    long fsize(FILE*fp)
      {
      long pos,size;
     
      pos=ftell(fp); /*sauve la position courante*/
      fseek(fp,0,SEEK_END);/*aller en fin*/
      size=ftell(fp);/*lire la taille*/
      fseek(fp,pos,SEEK_SET);/*revenir à la position initiale*/
      return size;
      }
     
     
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			Function generate key			//
    //								//
    //////////////////////////////////////////////////////////////////
    int generate_key ()
    {
    	int i, j, fd;
     
    	/*opening randoms file*/
    	if ((fd = open ("/dev/random", O_RDONLY)) == -1)
    		perror ("open error");
     
    	/*key read*/
    	if ((read (fd, key2, 16)) == -1)
    		perror ("read key error");
     
    	/*vector read*/
    	if ((read (fd, iv, 8)) == -1)
    		perror ("read iv error");
     
    	/*key view*/
    	printf("128 bit key:\n");
    	for (i = 0; i < 16; i++)
    		printf ("%d \t", key2[i]);
    	printf ("\n ------ \n");
     
    	/*vector view*/
    	printf("Initialization vector\n");
    	for (i = 0; i < 8; i++)
    		printf ("%d \t", iv[i]);
     
    	printf ("\n ------ \n");
    	close (fd);
    	return 0;
    }
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			Function encrypt			//
    //								//
    //////////////////////////////////////////////////////////////////
     
    int encrypt (int infd, int outfd)
    {
    	unsigned char outbuf[OP_SIZE];
    	int olen, tlen, n;
    	char inbuff[IP_SIZE];
    	EVP_CIPHER_CTX ctx;
    	EVP_CIPHER_CTX_init (&ctx);
    	EVP_EncryptInit (&ctx, EVP_bf_cbc (), key2, iv);
     
    	for (;;)
    	  {
    		  bzero (&inbuff, IP_SIZE);
     
    		  if ((n = read (infd, inbuff, IP_SIZE)) == -1)
    		    {
    			    perror ("read error");
    			    break;
    		    }
    		  else if (n == 0)
    			  break;
     
    		  if (EVP_EncryptUpdate (&ctx, outbuf, &olen, inbuff, n) != 1)
    		    {
    			    printf ("error in encrypt update\n");
    			    return 0;
    		    }
     
    		  if (EVP_EncryptFinal (&ctx, outbuf + olen, &tlen) != 1)
    		    {
    			    printf ("error in encrypt final\n");
    			    return 0;
    		    }
    		  olen += tlen;
    		  if ((n = write (outfd, outbuf, olen)) == -1)
    			  perror ("write error");
    	  }
    	EVP_CIPHER_CTX_cleanup (&ctx);
    	return 1;
    }
    suite dans le poste suivant

    mais j'ai un peu peur d'avoir fait une usine à gaz et je me demande en fait si SSL ne chiffrerait pas tout seul... et que du coup, j'aurais pas tout ça à faire...
    genre est-ce qaund on fait le SSL_read ou le SSL_write c'est chiffré ou pas...? (je n'arrive pas à avoir une réponse claire en regardant sur le net... bizarre...)
    merci pour votre aide...

  16. #16
    Membre confirmé Avatar de Bathou
    Inscrit en
    Mars 2007
    Messages
    179
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Mars 2007
    Messages : 179
    Par défaut
    serveur_SSL.c
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    /*SERVEUR*/
     
    #include "serveur_SSL.h"
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			Fonction Principale			//
    //								//
    //////////////////////////////////////////////////////////////////
    int main()
    {    
     
     
      int     err;        
      int     verify_client = OFF; /* To verify a client certificate, set ON */       
      int     listen_sock;        
      int     sock;       
      struct sockaddr_in sa_serv;         
      struct sockaddr_in sa_cli;          
      size_t client_len;          
      char    *str;       
      char     buf[100];     
      SSL_CTX         *ctx;        
      SSL            *ssl;       
      SSL_METHOD      *meth; 
      X509            *client_cert = NULL;    
      short int       s_port = 563;
     
     
      int address_size;
     
      FILE*fp,*fp_recu,*fpin,*fpout, *outfp, *infp, *decfp;
      int recp_fich=0,ks=0,longueur=0,n=0;
      unsigned char *cipher=NULL,*plain=NULL;
      int size=0,len=0;
      RSA *key=NULL;
      long taille_fichier;
     
      int flags1 = 0, flags2 = 0, outfd, infd, decfd;
      mode_t mode;
    	bzero (&mode, sizeof (mode));
     
    	flags1 = flags1 | O_RDONLY;
    	flags2 = flags2 | O_RDONLY;
    	flags2 = flags2 | O_WRONLY;
    	flags2 = flags2 | O_CREAT;
     
    	mode = mode | S_IRUSR;
    	mode = mode | S_IWUSR;
     
     
     
     
      ////////////////////////////////////////////////////////////////
      /*Initialization*/
     
      /* Load encryption & hashing algorithms for the SSL program */  
      SSL_library_init();     
     
      /* Load the error strings for SSL & CRYPTO APIs */      
      SSL_load_error_strings();       
     
      /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */     
      meth = SSLv3_method();  
     
      /* Create a SSL_CTX structure */    
      ctx = SSL_CTX_new(meth);        
      if (!ctx) 
          {             
          ERR_print_errors_fp(stderr);            
          exit(1);        
          }       
     
      /* Load the server certificate into the SSL_CTX structure */       
      if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <= 0) 
          {                    
          ERR_print_errors_fp(stderr);                    
          exit(1);       
          }       
     
      /* Load the private-key corresponding to the server certificate */          
      if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) 
          {               
          ERR_print_errors_fp(stderr);                
          exit(1);    
          }       
     
      /* Check if the server certificate and private-key matches */       
      if (!SSL_CTX_check_private_key(ctx)) 
          {                  
          fprintf(stderr,"Private key does not match the certificate public key\n");                  
          exit(1);    
          }      
     
      /*si on vérifie*/
      if(verify_client == ON)        
          {               
          /* Load the RSA CA certificate into the SSL_CTX structure */                
          if (!SSL_CTX_load_verify_locations(ctx, RSA_SERVER_CA_CERT, NULL)) 
              {                    
              ERR_print_errors_fp(stderr);                        
              exit(1);            
              }               
     
          /* Set to require peer (client) certificate verification */         
          SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);           
          /* Set the verification depth to 1 */               
          SSL_CTX_set_verify_depth(ctx,1);       
          }  
     
      printf("Initialization terminate\n\n");
     
      ////////////////////////////////////////////////////////////////
      /*SOCKET*/   
     
      /* Set up a TCP socket */       
      listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);        
      RETURN_ERR(listen_sock, "socket");          
      memset (&sa_serv, '\0', sizeof(sa_serv));       
      sa_serv.sin_family      = AF_INET;          
      sa_serv.sin_addr.s_addr = INADDR_ANY;       
      sa_serv.sin_port        = htons (s_port);     
     
      /* Server Port number */         
      err = bind(listen_sock, (struct sockaddr*)&sa_serv,sizeof(sa_serv));        
      RETURN_ERR(err, "bind");        
     
      /* Wait for an incoming TCP connection. */          
      err = listen(listen_sock, 5);                           
      RETURN_ERR(err, "listen");          
      client_len = sizeof(sa_cli);    
      printf("WAITING FOR CONNECTION\n\n");
     
      /* Socket for a TCP/IP connection is created */     
      sock = accept(listen_sock, (struct sockaddr*)&sa_cli, &client_len);     
      RETURN_ERR(sock, "accept");         
      close (listen_sock);    
      printf ("Connection from %lx, port %x\n", sa_cli.sin_addr.s_addr,sa_cli.sin_port);     
     
     
      ////////////////////////////////////////////////////////////////
      /*SSL*/      
     
      /* TCP connection is ready. */      
     
      /* A SSL structure is created */    
      ssl = SSL_new(ctx);     
      RETURN_NULL(ssl);       
     
      /* Assign the socket into the SSL structure (SSL and socket without BIO) */ 
      SSL_set_fd(ssl, sock);  
     
      /* Perform SSL Handshake on the SSL server */       
      err = SSL_accept(ssl);  RETURN_SSL(err);        
     
      /* Informational output (optional) */       
      printf("SSL connection using %s\n", SSL_get_cipher (ssl));     
      if (verify_client == ON)   
          {           
          /* Get the client's certificate (optional) */       
          client_cert = SSL_get_peer_certificate(ssl);        
          if (client_cert != NULL)            
              {               
              printf ("Client certificate:\n");                   
              str = X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);                  
              RETURN_NULL(str);                   
              printf ("\t subject: %s\n", str);                   
              free (str);                 
              str = X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0);                   
              RETURN_NULL(str);                   
              printf ("\t issuer: %s\n", str);                    
              free (str);                 
              X509_free(client_cert);     
              }       
          else                    
              printf("The SSL client does not have certificate.\n");  
          }       
     
      ////////////////////////////////////////////////////////////////
      /*------- DATA EXCHANGE - Receive message and send reply. -------*/ 
     
      printf("\n************************************");
      printf("\nDATA EXCHANGE\n");
     
      /* Receive data from the SSL client */      
      err = SSL_read(ssl, buf, sizeof(buf) - 1);      
      RETURN_SSL(err);        buf[err] = '\0';        
      printf ("Received %d chars:'%s'\n", err, buf);  
     
      /* Send data to the SSL client */   
      err = SSL_write(ssl, "This message is from the SSL server",strlen("This message is from the SSL server"));                 
      RETURN_SSL(err);        
     
     
          //////////////////////////////////////////////////////////////////
          /*GENERATION DES CLES*/
     
          /*taille de la clé*/
          ks = 1024;
     
          printf("Generating RSA keys [size = %d bits]\n", ks);
          /*appel de la fonction de génération des clés*/
          genkey(ks);
     
          /*affichage des fichiers contenant clé privée et clé publique*/
          printf("Private Key saved in %s file.\n", CLE_PRIVE);
          printf("Public Key saved in %s file.\n", CLE_PUBLIC);
          printf("Done.\n\n");
     
     
          //////////////////////////////////////////////////////////////////
          /*ENVOI DE LA CLE PUBLIQUE*/
     
          /*ouverture du fichier*/
          fp=fopen(CLE_PUBLIC,"rb");
          if (fp==NULL)
              {
              perror("call to open\n");
              exit(1);
              }
     
          /*envoi de la taille du fichier*/
          long taille =fsize(fp);
          taille=htonl(taille);
          longueur=sizeof(taille);
          int env_taille=SSL_write(ssl, &taille, longueur);
          if (env_taille==-1)
              {
              perror("call to send\n");
              exit(1);
              }
          printf("send file size ok\n");
     
     
     
          /*tant qu'on n'a pas tout envoyé, tant qu'on n'a pas atteint la fin du fichier*/
          fseek(fp,0,SEEK_SET);
          while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
              {
              /*on envoi*/
              int envoi=SSL_write(ssl, buf, n);
              if (envoi==-1)
                  {
                  perror("call to send\n");
                  exit(1);
                  }
              }
     
          /*fermeture du fichier*/
          fclose(fp);
          printf("send Public Key OK\n\n");
     
         //////////////////////////////////////////////////////////////////
          /*RECEPTION DU FICHIER CHIFFRE*/
     
     
          /*ouverture du fichier*/
          fp_recu=fopen(FICHIER_CLE_SYMETRIQUE_ENC,"wb");
          if (fp_recu==NULL)
              {
              perror("call to open\n");
              exit(1);
              }
     
          /*reception de la taille du fichier*/
          int recp_taille=SSL_read(ssl,&taille_fichier,sizeof(taille_fichier));
          if (recp_taille==-1)
             {
             perror("call to rcv taille\n");
             exit(1);
             }
          taille_fichier=ntohl(taille_fichier);
          printf("size file %d receive\n",taille_fichier);
          printf("Reception ...\n");
     
          /*tant que l'on a pas tout reçu*/
     
          while (taille_fichier > 0 && (recp_fich = SSL_read(ssl, buf, sizeof (buf))) > 0)
              {
              /*on recoi*/
              if(recp_fich <0)
                  {
                  perror("call to rcv\n");
                  exit(1);
                  }
     
              /*on écrit dans le fichier*/
              fwrite(buf,1,recp_fich,fp_recu);
     
              /*on diminue la taille*/
              taille_fichier -= recp_fich;
     
              /*RAZ buffer*/
              memset(&buf,0,sizeof(buf));
              }
     
          /*fermeture du fichier*/
          fclose(fp_recu); 
          printf("reception symétric key OK!\n\n");
     
          //////////////////////////////////////////////////////////////////
          /*DECHIFFREMENT DU-DIT FICHIER*/
     
          /*lecture de la clé privée*/
          key = readpemkeys(READSEC);
     
          /*ouverture du fichier input*/
          if(!(fpin = fopen(FICHIER_CLE_SYMETRIQUE_ENC, "rb"))) 
              {
              fprintf(stderr, "Error: Cannot locate input file.\n");
              exit(EXIT_FAILURE);
              }
     
          /*ouverture du fichier output*/
          fpout = fopen(FICHIER_CLE_SYMETRIQUE, "wb");
     
          /*taille de la clé rsa*/
          ks = RSA_size(key);
     
          /*allocation de la mémoire*/
          cipher = (unsigned char*)malloc(ks * sizeof(unsigned char));
          plain = (unsigned char*)malloc(ks * sizeof(unsigned char));
          printf("Decrypting '%s' file.\n", FICHIER_CLE_SYMETRIQUE_ENC);
     
          /*tant qu'on n'a pas atteint la fin du fichier*/
          while(!feof(fpin)) 
              {
              /*mise à zéro de cipher et plain*/
              memset(cipher, '\0', ks);
              memset(plain, '\0', ks);
     
              /*lecture de l'info dans le fichier input*/
              if ((len = fread(cipher, 1, ks, fpin)) == 0)
                break;
              /*déchiffrement*/
              size = rsa_decrypt(key, cipher, len, &plain);
              /*écriture dans le fichier out put*/
              fwrite(plain, 1, size, fpout);
              }
     
          /*fermeture des fichiers*/
          fclose(fpout);
          fclose(fpin);
     
          /*libération de la mémoire*/
          free(plain);
          free(cipher);
          RSA_free(key);
          printf("Decypting symetric file Done.\n\n");
     
      /*ouverture du fichier*/
      fp=fopen(FICHIER_CLE_SYMETRIQUE,"r");
      if (fp==NULL)
            {
            perror("call to open\n");
            exit(1);
            }
      fread(key2,sizeof(*key2),16,fp);
      fread (iv,sizeof(*iv),8,fp);
      int i=0;
      for (i = 0; i < 16; i++)
    		printf ("%d \t", key2[i]);
      printf("\n\n");
      for (i = 0; i < 8; i++)
    		printf ("%d \t", iv[i]);
      fclose(fp);
      printf("\n\n");
     
    //////////////////////////////////////////////////////////////////////
        printf("Reception...\n");
        /*ouverture du fichier*/
        fp_recu=fopen(FICHIER_ENC,"wb");
        if (fp_recu==NULL)
            {
            perror("call to open\n");
            exit(1);
            }
     
      /*reception de la taille du fichier*/
      recp_taille=SSL_read(ssl,&taille_fichier,sizeof(taille_fichier));
      if (recp_taille==-1)
          {
          perror("call to rcv taille\n");
          exit(1);
          }
      printf("taille fichier %d reçue\n",taille_fichier);
      printf("Reception file...\n");
     
      /*tant que l'on a pas tout reçu*/
     
      while (taille_fichier > 0 && (recp_fich = SSL_read(ssl, buf, sizeof (buf))) > 0)
        {
        /*on recoi*/
        if(recp_fich <0)
          {
          perror("call to rcv\n");
          exit(1);
          }
     
        /*on écrit dans le fichier*/
        fwrite(buf,1,recp_fich,fp_recu);
     
        /*on diminue la taille*/
        taille_fichier -= recp_fich;
     
    	bzero(&buf,sizeof(buf));
        }
     
     
      /*fermeture du fichier*/
      fclose(fp_recu);
      printf("Reception file ok\n\n");
     
    //////////////////////////////////////////////////////////////////////////
     
      /*déchiffrement*/
     /* printf("Decrypting File...\n");
    if ((outfp=fopen(FICHIER_ENC, "rb"))==NULL)
    	perror("open output file error");
     
    if ((decfp=fopen(FICHIER,"wb"))==NULL)
    	perror("open dec file error");
     
    decrypt(outfp, decfp);
    fclose(outfp);
    fclose(decfp);
    printf("The file is decrypt\n\n");*/
     
     
      if ((outfd = open (FICHIER_ENC, flags1, mode )) == -1)
    				    perror ("open output file error");
     
      if ((decfd = open (FICHIER, flags2, mode)) == -1)
    				    perror ("open output file error");
     
    			    decrypt (outfd, decfd);
     
    			    close (outfd);
    			    fsync (decfd);
    			    close (decfd);
    			    printf("The file is decrypt\n\n");
     
    //////////////////////////////////////////////////////////////////////////
     
     
      printf("\nEND DATA EXCHANGE\n");
      printf("************************************\n");
     
      ////////////////////////////////////////////////////////////////
      /*--------------- SSL closure ---------------*/     
     
      /* Shutdown this side (server) of the connection. */    
      err = SSL_shutdown(ssl);        
      RETURN_SSL(err);        
     
      /* Terminate communication on a socket */   
      err = close(sock);      
      RETURN_ERR(err, "close");      
     
      /* Free the SSL structure */        
      SSL_free(ssl); 
     
      /* Free the SSL_CTX structure */   
      SSL_CTX_free(ctx); 
     
      printf("Application terminate : good bye!\n");
     
      /*END*/
     
    }
    serveur_SSL.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    /*Headers*/
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
     
    #include <netdb.h>
    #include <unistd.h> 
    #ifdef __VMS
    #include <types.h>
    #include <socket.h>
    #include <in.h>
    #include <inet.h> 
    #else
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include "fcntl.h"
    #include "sys/stat.h"
    #include "unistd.h"
     
    #endif 
     
    /*OpenSSL headers*/
    #include <openssl/crypto.h>
    #include <openssl/ssl.h>
    #include <openssl/err.h> 
    #include "openssl/bio.h"
    #include "openssl/evp.h"
    #include "openssl/rsa.h"
    #include "openssl/des.h"
    #include "openssl/blowfish.h"
     
     
     
     
    #define RSA_SERVER_CERT     "serveur_ssl_cert.pem"
    #define RSA_SERVER_KEY          "serveur_ssl_priv_key.key" 
    #define RSA_SERVER_CA_CERT "../cassl/cassl_cert.pem"
    #define RSA_SERVER_CA_PATH   "bathou1" 
    #define ON 1
    #define OFF 0 
    #define RETURN_NULL(x) if ((x)==NULL) exit(1)
    #define RETURN_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
    #define RETURN_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(1); } 
     
    #define READPUB 0
    #define READSEC 1
     
    unsigned char key2[16];
    unsigned char iv[8];
     
    /*fichiers PEM pour clés publiques/privées*/
    #define CLE_PRIVE "cle_privee.pem"
    #define CLE_PUBLIC "cle_publique.pem"
     
    #define FICHIER_ENC "fichier_chiffre_recu.bin"
    #define FICHIER "fichier_dec.txt"
    #define CLE_PUB_CLI "cle_publique_client.pem"
     
    #define FICHIER_CLE_SYMETRIQUE "cle_symétrique.txt"
    #define FICHIER_CLE_SYMETRIQUE_ENC "cle_symétrique_enc.bin"
     
    #define IP_SIZE 1024
    #define OP_SIZE 1032
     
     
     
    void genkey(int size);
    long fsize(FILE*fp);
    int rsa_decrypt(RSA *key, unsigned char *cipher, int len, unsigned char **plain);
    RSA* readpemkeys(int type);
    int decrypt (int infd, int outfd);
    //int decrypt (FILE*infd, FILE*outfd);
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			GenerationKey fonction			//
    //								//
    //////////////////////////////////////////////////////////////////
    void genkey(int size)
    {
      RSA *key=NULL;
      FILE *fp;
     
      ////////////////////////////////////////////////////////////////
     
      /*génération de la clé*/
      if((key = RSA_generate_key(size,3,NULL,NULL)) == NULL) 
          {
          fprintf(stderr,"%s\n",ERR_error_string(ERR_get_error(),NULL));
          exit(EXIT_FAILURE);
          }
     
      /*vérification de la clé*/
      if(RSA_check_key(key) < 1) 
          {
          fprintf(stderr,"Error: Problems while generating RSA Key.\nRetry.\n");
          exit(EXIT_FAILURE);
          }
     
      ////////////////////////////////////////////////////////////////
     
      /*CLE PRIVEE*/
     
      /*ouverture du fichier de clé privée*/
      fp=fopen(CLE_PRIVE,"wb");
      /*écriture de la clé privée dans son fichier*/
      if(PEM_write_RSAPrivateKey(fp,key,NULL,NULL,0,0,NULL) == 0) 
          {
          fprintf(stderr,"Error: problems while writing RSA Private Key.\n");
          exit(EXIT_FAILURE);
          }
      /*fermeture du fichier*/
      fclose(fp);
     
      ////////////////////////////////////////////////////////////////
     
      /*CLE PUBLIQUE*/
     
      /*ouverture du fichier de clé publique*/
      fp=fopen(CLE_PUBLIC,"wb");
      /*écriture de la clé publique dans son fichier*/
      if(PEM_write_RSAPublicKey(fp,key) == 0) 
          {
          fprintf(stderr,"Error: problems while writing RSA Public Key.\n");
          exit(EXIT_FAILURE);
          }
      /*fermeture du fichier*/
      fclose(fp);
     
      ///////////////////////////////////////////////////////////////
     
      /*libération de la mémoire pour le contexte RSA*/
      RSA_free(key);
      return;
    }
     
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			fonction Fsize				//
    //								//
    //////////////////////////////////////////////////////////////////
    long fsize(FILE*fp)
      {
      long pos,size;
     
      pos=ftell(fp); /*sauve la position courante*/
      fseek(fp,0,SEEK_END);/*aller en fin*/
      size=ftell(fp);/*lire la taille*/
      fseek(fp,pos,SEEK_SET);/*revenir à la position initiale*/
      return size;
      }
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			RSA Decrypt Function			//
    //								//
    //////////////////////////////////////////////////////////////////
     
    int rsa_decrypt(RSA *key, unsigned char *cipher, int len, unsigned char **plain)
    {
      int plen=0;
     
      /*on déchiffre*/
      if((plen = RSA_private_decrypt(len, cipher, *plain, key, RSA_PKCS1_PADDING)) == -1) 
          {
          fprintf(stderr, "%s\n", ERR_error_string(ERR_get_error(), NULL));
          exit(EXIT_FAILURE);
          } else
        return plen;
    }
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			read PEM keys function			//
    //								//
    //////////////////////////////////////////////////////////////////
    RSA* readpemkeys(int type)
    {
      FILE *fp;
      RSA *key=NULL;
     
      ////////////////////////////////////////////////////////////////
     
      /*si clé publique*/
      if(type == READPUB) 
          {
          /*ouverture du fichier*/
          if((fp = fopen(CLE_PUBLIC,"r")) == NULL) 
              {
              fprintf(stderr,"Error: Public Key file doesn't exists.\n");
              exit(EXIT_FAILURE);
              }
          /*lecture de la clé publique*/
          if((key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL)) == NULL) 
              {
              fprintf(stderr,"Error: problems while reading Public Key.\n");
              exit(EXIT_FAILURE);
              }
          /*fermeture du fichier*/
          fclose(fp);
          /*retourne la valeur de la clé lue*/
          return key;
          }
     
      ////////////////////////////////////////////////////////////////
     
      /*si clé privée*/
      if(type == READSEC) 
          {
          /*ouverture du fichier*/
          if((fp = fopen(CLE_PRIVE,"r")) == NULL) 
              {
              fprintf(stderr,"Error: Private Key file doesn't exists.\n");
              exit(EXIT_FAILURE);
              }
          /*lecture de la clé privée*/
          if((key = PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL)) == NULL) 
              {
              fprintf(stderr,"Error: problmes while reading Private Key.\n");
              exit(EXIT_FAILURE);
              }
          /*fermeture du fichier*/
          fclose(fp);
          /*verification de la clé*/
          /*si =-1 échou*/
          if(RSA_check_key(key) == -1) 
              {
              fprintf(stderr,"Error: Problems while reading RSA Private Key in '%s' file.\n",CLE_PRIVE);
              exit(EXIT_FAILURE);
              } 
          /*si =0 échec*/
          else if(RSA_check_key(key) == 0) 
              {
              fprintf(stderr,"Error: Bad RSA Private Key readed in '%s' file.\n",CLE_PRIVE);
              exit(EXIT_FAILURE);
              }
          else/*on retourne la clé*/
            return key;
          }
      return key;
    }
     
    //////////////////////////////////////////////////////////////////
    //								//
    //			Function decrypt			//
    //								//
    //////////////////////////////////////////////////////////////////
     
    int decrypt (int infd, int outfd)
    //int decrypt (FILE*infd, FILE*outfd)
    {
    	unsigned char outbuf[IP_SIZE];
    	int olen, tlen, n;
    	char inbuff[OP_SIZE];
    	EVP_CIPHER_CTX ctx;
    	EVP_CIPHER_CTX_init (&ctx);
    	EVP_DecryptInit (&ctx, EVP_bf_cbc (), key2, iv);
     
    	for (;;)
    	  {
    			memset(&inbuff, 0, OP_SIZE);	  
    		//	n=fread(inbuff,1,sizeof(inbuff),infd);
    		  /*lecture du texte*/
    		  n=read (infd, inbuff, OP_SIZE);
    		  if (n== -1)
    		    {
    			    perror ("read error");
    			    break;
    		    }
    		  else if (n == 0)
    			  break;
    		memset(&outbuf, 0, IP_SIZE);
    		//  bzero (&outbuf, IP_SIZE);
    		  /*déchiffrement de la plus grande partie*/
    		  if (EVP_DecryptUpdate (&ctx, outbuf, &olen, inbuff, n) != 1)
    		    {
    			    printf ("error in decrypt update\n");
    			    return 0;
    		    }printf("ok!\n");
     
    		  /*déchiffrement de la fin*/
    		  if (EVP_DecryptFinal (&ctx, outbuf + olen, &tlen) != 1)
    		    {
    			    perror("error in decrypt final\n");
    				ERR_print_errors_fp(stderr);
     
    			    return 0;
    		    }
    		  olen += tlen;
     
    		/*écriture dans le fichier*/
    		n = write (outfd, outbuf, olen);
    		//n=fwrite(outbuf, 1, sizeof(outbuf),outfd);
    		  if (n == -1)
    			  perror ("write error");
    	  }
     
    	EVP_CIPHER_CTX_cleanup (&ctx);
    	return 1;
    }
    voila ^^

Discussions similaires

  1. récupération clé publique d'un certificat
    Par guy_s dans le forum Bibliothèques et frameworks
    Réponses: 5
    Dernier message: 15/09/2016, 16h40
  2. Réponses: 4
    Dernier message: 11/06/2004, 16h27
  3. Réponses: 3
    Dernier message: 26/05/2004, 17h38
  4. Oracle Designer: récupération d'une vue dans la base
    Par BILLYPATOU dans le forum Designer
    Réponses: 2
    Dernier message: 19/03/2004, 11h08
  5. Réponses: 2
    Dernier message: 20/02/2004, 08h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo