• STATISTIQUES
  • Il y a eu un total de 0 membres et 7830 visiteurs sur le site dans les dernières 24h pour un total de 7 830 personnes!
    Membres: 2 450
    Discussions: 3 572
    Messages: 32 822
    Tutoriels: 77
    Téléchargements: 38
    Sites dans l'annuaire: 58


  • ANNUAIRE
  • [EN] hax.tor
    50 level de challenges mélangés
    Challenges
    [FR] apprendre-a-manipuler
    Site d'apprentissage de la manipulation d'autrui.
    Hacking
    [FR] frameip
    le site de partage des connaissances du monde TCPIP
    Protocole
    [FR] Developpez.net
    Un forum communautaire qui se veut pour les développeurs en générale. Avec presque 500 000 membr...
    Programmation
    [EN] This is legal
    Basic: 10, Realistic: 5, Programming: 1, Bonus: 11, SQL: 2, Encryption: 6, Application: 4, User Contributed: 3
    Challenges
    [EN] Net Force
    Javascript: 9, Java Applets: 6, Cryptography: 16, Exploits: 7, Cracking: 14, Programming: 13, Internet: 15, Steganograph...
    Challenges
    [FR] WeChall
    Audio: 3, Coding: 11, Cracking: 9, Crypto: 18, Encoding: 11, Exploit: 44, Forensics: 1, Fun: 6, HTTP: 6, Image: 8, Java:...
    Challenges

  • DONATION
  • Si vous avez trouvé ce site internet utile, nous vous invitons à nous faire un don du montant de votre choix via Paypal. Ce don servira à financer notre hébergement.

    MERCI!




Note de ce sujet :
  • Moyenne : 0 (0 vote(s))
  • 1
  • 2
  • 3
  • 4
  • 5
Chiffrement RSA en php et java
28-06-2013, 00h56 (Modification du message : 28-06-2013, 00h57 par InstinctHack.)
Message : #1
InstinctHack Hors ligne
Posting Freak
*



Messages : 1,366
Sujets : 184
Points: 299
Inscription : Dec 2011
Chiffrement RSA en php et java
Salut,

Je voudrais faire du chiffrement asymétrique avec RSA dans une application java et pouvoir le déchiffrer dans une application php (et vice-versa si possible Big Grin )
Ca fait une semaine que je cherche, mais je pige rien et ça commence à me gonfler de pas réussir >_<"

voilà mon code java :
Code JAVA :

import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.math.BigInteger;
public class rsa
{
    public final static int KEY_SIZE = 512;
    private RSAPublicKey publicKey;
    private RSAPrivateKey privateKey;
    /**
     * Translates the specified byte array into Base64 string.
     *
     * @param buf the byte array (not null)
     * @return the translated Base64 string (not null)
     */

    public static String base64Encode(byte[] buf){
        char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
        int size = buf.length;
        char[] ar = new char[((size + 2) / 3) * 4];
        int a = 0;
        int i=0;
        while(i < size){
            byte b0 = buf[i++];
            byte b1 = (i < size) ? buf[i++] : 0;
            byte b2 = (i < size) ? buf[i++] : 0;

            int mask = 0x3F;
            ar[a++] = ALPHABET[(b0 >> 2) & mask];
            ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
            ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
            ar[a++] = ALPHABET[b2 & mask];
        }
        switch(size % 3){
        case 1: ar[--a]  = '=';
        case 2: ar[--a]  = '=';
        }
        return new String(ar);
    }

    /**
     * Translates the specified Base64 string into a byte array.
     *
     * @param s the Base64 string (not null)
     * @return the byte array (not null)
     */

    public static byte[] base64Decode(String s){
        char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
        int[] toInt   = new int[128];
        for(int i=0; i< ALPHABET.length; i++)
            toInt[ALPHABET[i]]= i;
        int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
        byte[] buffer = new byte[s.length()*3/4 - delta];
        int mask = 0xFF;
        int index = 0;
        for(int i=0; i< s.length(); i+=4){
            int c0 = toInt[s.charAt( i )];
            int c1 = toInt[s.charAt( i + 1)];
            buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
            if(index >= buffer.length){
                return buffer;
            }
            int c2 = toInt[s.charAt( i + 2)];
            buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
            if(index >= buffer.length){
                return buffer;
            }
            int c3 = toInt[s.charAt( i + 3 )];
            buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
        }
        return buffer;
    }


    public static void main(String[] args)
    {
        rsa rsa = new rsa();
        rsa.generateKeyPair();
        String plaintext = "hello world hello world";
        System.out.println("plaintext  = " + plaintext);
        System.out.println("privateKey = "+base64Encode(new String(rsa.getPrivateKeyInBytes()).getBytes()));
        System.out.println("publicKey  = "+base64Encode(new String(rsa.getPublicKeyInBytes()).getBytes()));
        byte[] ciphertext = rsa.crypt(plaintext);
        System.out.println("ciphertext = " + base64Encode(new String(ciphertext).getBytes()));
        String plaintext2 = rsa.decrypt(ciphertext);
        System.out.println("plaintext2 = " + plaintext2);
    }

    public RSAPublicKey getPublicKey()
    {
        return publicKey;
    }

    public byte[] getPublicKeyInBytes()
    {
        return publicKey.getEncoded();
    }

    public RSAPrivateKey getPrivateKey()
    {
        return privateKey;
    }

    public byte[] getPrivateKeyInBytes()
    {
        return privateKey.getEncoded();
    }

    public void generateKeyPair()
    {
        try
        {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            keyPairGen.initialize(KEY_SIZE, new SecureRandom());
            KeyPair kp = keyPairGen.generateKeyPair();
            publicKey = (RSAPublicKey)kp.getPublic();
            privateKey = (RSAPrivateKey)kp.getPrivate();
        }
        catch (Exception e) {System.out.println(e);}
    }

    public byte[] crypt(String plaintext)
    {
        byte[]        plaintext_etape1= plaintext.getBytes();
        BigInteger    plaintext_etape2= new BigInteger(addOneByte(plaintext_etape1));
        BigInteger    plaintext_etape3= plaintext_etape2.modPow(publicKey.getPublicExponent(), publicKey.getModulus());
        byte[] plaintext_etape4     = plaintext_etape3.toByteArray();
        return plaintext_etape4;
    }

    public String decrypt(byte[] ciphertext)
    {
        BigInteger ciphertext_etape1 = new BigInteger(ciphertext);
        BigInteger ciphertext_etape2 = ciphertext_etape1.modPow(privateKey.getPrivateExponent(), privateKey.getModulus());
        byte[] ciphertext_etape3 = ciphertext_etape2.toByteArray();
        byte[] ciphertext_etape4 = removeOneByte(ciphertext_etape3);
        return new String(ciphertext_etape4);
    }

    /**
    * Ajoute un byte de valeur 1 au début du message afin d'éviter que ce dernier
    * ne corresponde pas à un nombre négatif lorsqu'il sera transformé en
    * BigInteger.
    */

    private static byte[] addOneByte(byte[] input)
    {
        byte[] result = new byte[input.length+1];
        result[0] = 1;
        for (int i = 0; i < input.length; i++)
            result[i+1] = input[i];
        return result;
    }

    /**
    * Retire le byte ajouté par la méthode addOneByte.
    */

    private static byte[] removeOneByte(byte[] input)
    {
        byte[] result = new byte[input.length-1];
        for (int i = 0; i < result.length; i++)
            result[i] = input[i+1];
        return result;
    }
}
 


la sortie produite :
Code :
plaintext  = hello world hello world
privateKey = MO+/vQFUAgEAMA0GCSrvv71I77+977+9DQEBAQUABO+/vQE+MO+/vQE6AgEAAkEA77+9Njzvv71qYzt277+9T0jvv70RBWkZ77+977+977+977+977+977+977+977+977+9HgTvv70h77+977+977+9du+/vVfvv709IO+/ve+/ve+/vd+E77+977+977+977+9GXbvv71I77+977+977+9Ze+/vRtT77+9PH5K77+9AgMBAAECQFDvv71777+9Ru+/vVBy77+977+977+9Ae+/vTHvv73vv71wDBPvv71mf++/ve+/vSZ277+9cR/Dju+/vQXvv71KPu+/ve+/vSl077+977+9We+/vVkf77+977+9TncNdO+/ve+/vR3NoD7vv70uL++/vQIhAO+/vdaH77+9NmXvv73vv71t77+90Yzvv73vv70V77+977+977+977+9E++/ve+/ve+/vSpS77+9G39aSA4tAiEA77+9IwHvv71G77+9Nu+/vU1c77+90anvv71MKU8xNe+/vSbvv73vv70v77+9LO+/ve+/vTjvvLkCIHQD77+936YCZzPvv71Z77+977+9Xe+/ve+/vRQOA++/ve+/vdeYKO+/vWVb77+9VxDvv73vv73vv70CIErvv709Zu+/ve+/ve+/vUAZ77+977+977+9YgLXrTDvv71va++/ve+/vRTvv70q77+977+9cGjvv73vv70pAiEA77+9Zk/vv714T33vv73Irc2lKzDvv70PJ1di77+977+977+977+9I9CR77+977+977+9TmTvv70=
publicKey  = MFwwDQYJKu+/vUjvv73vv70NAQEBBQADSwAwSAJBAO+/vTY877+9amM7du+/vU9I77+9EQVpGe+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/vR4E77+9Ie+/ve+/ve+/vXbvv71X77+9PSDvv73vv73vv73fhO+/ve+/ve+/ve+/vRl277+9SO+/ve+/ve+/vWXvv70bU++/vTx+Su+/vQIDAQAB
ciphertext = AO+/vXcrcu+/vThb1J3vv70S77+9O++/ve+/ve+/vTDvv71gfu+/ve+/ve+/ve+/vRTvv71fQ0Uiajfvv70U77+977+9Tizvv73vv71xEMqGKe+/ve+/vduX77+977+9eO+/vQ8b77+977+97q6Sfizvv73vv70=
plaintext2 = hello world hello world
( oups ma clé privée... :p )

et mon code php
Code PHP :

<?php
$privKey='';
$pubKey='';

/*
$res = openssl_pkey_new(
        array(
                "digest_alg" => "sha512",
                "private_key_bits" => 4096,
                "private_key_type" => OPENSSL_KEYTYPE_RSA,
        )
);

openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res)["key"];
*/


$data=file('log',FILE_IGNORE_NEW_LINES);
$privKey="-----BEGIN PRIVATE KEY-----"  .PHP_EOL.chunk_split(explode(' = ',$data[1])[1])        ."-----BEGIN PRIVATE KEY-----";
$pubKey ="-----BEGIN PUBLIC KEY-----"   .PHP_EOL.chunk_split(explode(' = ',$data[2])[1])        ."-----END PUBLIC KEY-----";

$cipher=base64_decode(explode(' = ',$data[3])[1]);

var_dump($data);
echo $privKey.PHP_EOL.PHP_EOL;
echo $pubKey.PHP_EOL.PHP_EOL;
echo $cipher.PHP_EOL.PHP_EOL;

openssl_private_decrypt($cipher,$decrypted,$privKey);
echo $decrypted;
echo PHP_EOL;
 


Le problème c'est que la clé privée (et sûrement la public aussi mais pas tester) n'est pas valide, donc je mis prend mal, sauf que je sais vraiment pas commen faire du coup :/
Des idées ?
Merci d'avance Smile
Citation :un jour en cours de java j'ai attrapé les seins d'une fille mais elle m'a frappé en disant "c'est privé !!"
j'ai pas compris pourquoi, je croyais qu'on était dans la même classe
+1 (0) -1 (0) Répondre
28-06-2013, 01h31
Message : #2
Yttrium Hors ligne
Membre actif
*



Messages : 106
Sujets : 14
Points: 48
Inscription : Jul 2012
RE: Chiffrement RSA en php et java
Pour du chiffrement asymétrique, la personne qui souhaite envoyer le message n'a pas besoin de la clef privée, uniquement la clef publique, la clef privée étant utilisé par le récepteur pour lire le message.
Tu doit donc récupéré la clef, chiffrer, envoyer, utilisé la clef secrète qui est stockée et déchiffrer.

Dans ton code Java, tu encode tes clefs en base64, mais je ne te voie pas les décoder en base64 dans le code php.

J'espère que j'ai put t'aider !
BufferoverfloW

Всё минется, одна правда останется
+1 (0) -1 (0) Répondre
28-06-2013, 01h37
Message : #3
InstinctHack Hors ligne
Posting Freak
*



Messages : 1,366
Sujets : 184
Points: 299
Inscription : Dec 2011
RE: Chiffrement RSA en php et java
Oui, je sais bien, mais là c'est pour du débug hein, je m'en fous Smile

Pour l'histoire de l'encodage c'est parce que openssl veut des clés encoder, donc justement faut pas décoder (gg tu m'as mis tellement le doute et donner de l'espoir que j'ai lacher une larme :p )
Citation :un jour en cours de java j'ai attrapé les seins d'une fille mais elle m'a frappé en disant "c'est privé !!"
j'ai pas compris pourquoi, je croyais qu'on était dans la même classe
+1 (0) -1 (0) Répondre
28-06-2013, 10h31
Message : #4
b0fh Hors ligne
Membre actif
*



Messages : 210
Sujets : 17
Points: 309
Inscription : Jul 2012
RE: Chiffrement RSA en php et java
Hello,

Bon, j'ai la flemme de vérifier exactement pourquoi ça coince, mais je n'arrive pas à décoder tes clefs. La documentation de getEncoded() n'est pas très parlante malheureusement, mais c'est possible que ça soit un truc bizarre. Peut-être auras-tu plus de chance en générant les clefs avec openssl et en les important dans Java ensuite ?

Par contre, implémenter ton chiffrement à la main avec une exponentiation modulaire est problématique. RSA ne donne une sécurité correcte que si le plaintext est random et d'une taille proche de celle du module. Tu devrais utiliser un padding standard comme PKCS#1.
+1 (0) -1 (0) Répondre


Sujets apparemment similaires…
Sujet Auteur Réponses Affichages Dernier message
  Meilleur mode pour le chiffrement par bloc Serphentas 1 1,521 08-03-2016, 20h43
Dernier message: Serphentas
  [Php] chiffrement asymétrique avec OpenSSL InstinctHack 5 2,848 20-01-2013, 22h56
Dernier message: b0fh

Atteindre :


Utilisateur(s) parcourant ce sujet : 1 visiteur(s)
N-PN
Accueil | Challenges | Tutoriels | Téléchargements | Forum | Retourner en haut