首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加密python/解密android

加密python/解密android
EN

Stack Overflow用户
提问于 2011-06-07 06:55:32
回答 4查看 2.4K关注 0票数 3

我编写了两个代码,一个用python,另一个用android (eclipse)进行加密和解密。现在,我想使用python加密我的数据,并将其发送到android进行解密。

如何让两个不同的平台对数据进行加密/解密?!每个平台都有自己的加密和解密方法,那么我如何让它们相互通信并发送数据,并让android提取所传输的确切信息?

需要帮助!!

EN

回答 4

Stack Overflow用户

发布于 2011-06-09 04:55:05

Python代码:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2011-06-09 05:02:02

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2011-12-27 01:42:52

TLS可以用来以兼容的方式安全地传输数据。

Python ssl server-side

另外,如果您使用http协议进行通信,那么已经有一些高级库可能对您隐藏了所有血淋淋的细节;只需提供客户端/服务器证书并发出适当的请求即可。

Https Connection Android

它可能会让您避免重新实现许多糟糕的安全特性,比如forward secrecy

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6258935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档