2011-06-06 5 views
3

J'ai fait 2 codes un en python et l'autre en android (eclipse) pour le cryptage et le décryptage. Maintenant, je veux crypter mes données en utilisant python et l'envoyer à l'android pour le décrypter.Encryption python/Decryption android

Comment faire deux plates-formes différentes pour crypter/décrypter les données ?! Chaque plate-forme a sa propre façon de faire le cryptage et le décryptage, alors comment puis-je les faire se parler et envoyer des données et Android extrait les informations exactes qui ont été transmises?

Besoin d'aide !!

+0

Est-ce que GenerateSalt() est une solution? – SGLGG

+1

Publiez le code qui effectue le chiffrement/déchiffrement. –

+0

Quel algorithme de chiffrement utilisez-vous? – jterrace

Répondre

0

code Python:

def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024): 
    if not out_filename: 
     out_filename = in_filename + '.enc' 

    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16)) 
    encryptor = AES.new(key, AES.MODE_CBC, iv) 
    filesize = os.path.getsize(in_filename) 

    with open(in_filename, 'rb') as infile: 
     with open(out_filename, 'wb') as outfile: 
      outfile.write(struct.pack('<Q', filesize)) 
      outfile.write(iv) 

      while True: 
       chunk = infile.read(chunksize) 
       if len(chunk) == 0: 
        break 
       elif len(chunk) % 16 != 0: 
        chunk += ' ' * (16 - len(chunk) % 16) 

       outfile.write(encryptor.encrypt(chunk)) 

def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024): 
    if not out_filename: 
     out_filename = os.path.splitext(in_filename)[0] 

    with open(in_filename, 'rb') as infile: 
     origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] 
     iv = infile.read(16) 
     decryptor = AES.new(key, AES.MODE_CBC, iv) 

     with open(out_filename, 'wb') as outfile: 
      while True: 
       chunk = infile.read(chunksize) 
       if len(chunk) == 0: 
        break 
       outfile.write(decryptor.decrypt(chunk)) 

      outfile.truncate(origsize) 
0
Android Code: 
public static final int SALT_LENGTH = 20; 
public static final int PBE_ITERATION_COUNT = 1000; 

private static final String RANDOM_ALGORITHM = "SHA1PRNG"; 
private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; 
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; 

private static final String TAG = Act.class.getSimpleName(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    try { 

     String password = "password"; 
     String plainText = "plaintext message to be encrypted"; 

     // byte[] salt = generateSalt(); 
     byte[] salt = "dfghjklpoiuytgftgyhj".getBytes(); 
     Log.i(TAG, "Salt: " + salt.length + " " + HexEncoder.toHex(salt)); 
     PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT, 256); 
     SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGORITHM); 
     SecretKey tmp = factory.generateSecret(pbeKeySpec); 
     SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); 
     byte[] key = secret.getEncoded(); 
     Log.i(TAG, "Key: " + HexEncoder.toHex(key)); 

     // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT); 

     Cipher encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); 

     // byte[] encryptionSalt = generateSalt(); 
     // Log.i(TAG, "Encrypted Salt: " + encryptionSalt.length + " " + HexEncoder.toHex(encryptionSalt)); 
     // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); 
     // byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); 
     Log.i(TAG, encryptionCipher.getParameters() + " "); 
     byte[] iv = generateIv(); 
     IvParameterSpec ivspec = new IvParameterSpec(iv); 

     encryptionCipher.init(Cipher.ENCRYPT_MODE, secret, ivspec); 
     byte[] encryptedText = encryptionCipher.doFinal(plainText.getBytes()); 
     Log.i(TAG, "Encrypted: " + HexEncoder.toHex(encryptedText)); 

     Cipher decryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); 
     decryptionCipher.init(Cipher.DECRYPT_MODE, secret, ivspec); 
     byte[] decryptedText = decryptionCipher.doFinal(encryptedText); 
     Log.i(TAG, "Decrypted: " + new String(decryptedText)); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

private byte[] generateSalt() throws NoSuchAlgorithmException { 
    SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); 
    byte[] salt = new byte[SALT_LENGTH]; 
    random.nextBytes(salt); 
    return salt; 
} 

private byte[] generateIv() throws NoSuchAlgorithmException { 
    SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); 
    byte[] iv = new byte[16]; 
    random.nextBytes(iv); 
    return iv; 
} 

}

+0

J'ai quelques problèmes dans le code android en fait .. pourriez-vous plz ce qui ne va pas avec ?? ? Le "HexEncoder.toHex()" me donne une erreur qu'elle n'est pas définie ... aussi la méthode generateSalt() indique qu'elle n'est pas utilisée. Donc, de l'aide est nécessaire .. et Thx! – SGLGG

0

TLS pourrait être utilisé pour transmettre en toute sécurité les données d'une manière compatible.

Python ssl server-side

Si en plus vous utilisez le protocole HTTP pour la communication alors il y a déjà des bibliothèques de haut niveau qui pourraient se cacher tous les détails sordides de vous; fournissez simplement des certificats client/serveur et faites les demandes appropriées.

Https Connection Android

Il pourrait vous sauver de réimplémentant mal de nombreuses fonctionnalités de sécurité telles que forward secrecy.

0

Si vous êtes satisfait de mcrypt en utilisant AES CBC, il y a une solution simple décrite à http://laurentcharignon.com/blog/?p=37 "interlangage chiffrement/déchiffrement AES CBC (Python/Java/PHP)".