DES decrypt/encrypt java 到 python (帮助翻译)

DES decrypt/encrypt java to python (help in translate)

我需要将 java 中的短代码翻译成 python 3.

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class DesEncrypterPdys {
    private static DesEncrypterPdys desEncrypter;
    private static Cipher ecipher;
    private static Cipher dcipher;

    private DesEncrypterPdys() throws DesEncrypterException{
        try {
            if(ecipher == null || dcipher == null){
                String cryptoKey;
                cryptoKey = "RAMPOLO S.O. Plokity Lopiokiujhygh ;)";

                SecretKey k = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(cryptoKey.getBytes()));

                ecipher = Cipher.getInstance("DES");
                dcipher = Cipher.getInstance("DES");
                ecipher.init(Cipher.ENCRYPT_MODE, k);
                dcipher.init(Cipher.DECRYPT_MODE, k);
            }
        }catch (Exception e) {
            throw new DesEncrypterException(e);
        }
    }

    public static DesEncrypterPdys getInstance() throws DesEncrypterException{
        if (desEncrypter == null || ecipher == null || dcipher == null) {
            desEncrypter = new DesEncrypterPdys();
        }
        return desEncrypter;
    }

    public String encrypt(String str) throws DesEncrypterException{
        try {
            if(str == null) return null;
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string

            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
            throw new DesEncrypterException(e);
        } catch (IllegalBlockSizeException e) {
            throw new DesEncrypterException(e);
        }
        catch (java.io.IOException e) {
            throw new DesEncrypterException(e);
        }
    }

    public String decrypt(String str) throws DesEncrypterException{
        try {
            if(str == null) return null;
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");

        } catch (javax.crypto.BadPaddingException e) {
            throw new DesEncrypterException(e);
        } catch (IllegalBlockSizeException e) {
            throw new DesEncrypterException(e);
        } catch (java.io.IOException e) {
            throw new DesEncrypterException(e);
        }
    }

}

我试过使用这样的东西:

import pyDes as pds
import base64 as b64


cryptoKey = "RAMPOLO S.O. Plokity Lopiokiujhygh ;)";
data = b" " # here should be a data for decrypting

k = pds.des(cryptoKey, pds.ECB, b"[=14=][=14=][=14=][=14=][=14=][=14=][=14=][=14=]", pad=None, padmode=pds.PAD_PKCS5)
d = k.encrypt(data)
print("Encrypted: %r" % d)
print("Decrypted: %r" % k.decrypt(d))
print(b64.b64encode(d))

可惜运气不好:/

我要接收的是一个加解密密码的小程序。不幸的是,我遇到了密码太长的问题(?)。一旦我能够翻译一段类似的代码,但旧案例与 pydes 文档中的案例相对应可能是运气问题。现在不一样了... 有人能帮我把这个 java 代码翻译成 python 吗?

当 运行 您的代码返回的错误是:

>>> import pyDes as pds
>>> import base64 as b64
>>> cryptoKey = "RAMPOLO S.O. Plokity Lopiokiujhygh ;)"
>>> data = b"qwertyuiop" # Random gibberish
>>> k = pds.des(cryptoKey, pds.ECB, b"[=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=]", pad=None, padmode=pds.PAD_PKCS5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pyDes.py", line 400, in __init__
    raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")
ValueError: Invalid DES key size. Key must be exactly 8 bytes long.

如果您查看 pyDES 的 Github 文档,它指定 DES 加密的密钥长度应为 8 个字节,而您的要长得多。您需要使用更短的密钥,然后才能正常工作。

>>> k = pds.des('12345678', pds.ECB, b"[=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=]", pad=None, padmode=pds.PAD_PKCS5)
>>> k
<pyDes.des object at 0x7fc4ade1f9d0>

重要的旁注,从安全的角度来看,您应该避免使用 DES,因为它完全不符合当今的标准,即使是 Wikipedia page (which is not a great source of cryptographic knowledge) shows that DES breaking is feasible. Also ECB mode is broken as it doesn't provide any security guarantees because each block is encrypted in the exact same way, check this