【问题标题】:Encryption Diff Between Java and C#Java 和 C# 之间的加密差异
【发布时间】:2023-03-16 21:53:02
【问题描述】:

您好,我想弄清楚如何复制在 C# 中但在 Java 中完成的文本加密。仍然让我感到困惑并且似乎无法找到答案的部分代码是在 C# 中:

PasswordDeriveBytes myPass = new PasswordDeriveBytes(String Password, byte[] Salt);
Trp.Key = myPass.GetBytes(24);
Trp.IV = myPass.GetBytes(8);

基本上,Java 中这段代码的等价物是什么? 更新:使用提供的 PasswordDeriveBytes 代码(第二个 sn-p)我能够完美地复制 C# 代码。谢谢 Maarten Bodewes。

BASE64Encoder base64 = new BASE64Encoder();
PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(passWord, saltWordAsBytes);
byte[] keyBytes = i_Pass.getBytes(24);
byte[] ivBytes = i_Pass.getBytes(8);
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(keyBytes, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(ivBytes);
c3des.init (Cipher.ENCRYPT_MODE, myKey, ivspec);
encrytpedTextAsByte  = c3des.doFinal(plainTextAsBytes);
encryptedText  = base64.encode(encrytpedTextAsByte);

但似乎无法让它跨平台工作。基本上解码代码已设置(我无法在 C# 3.5 中更改),我正在尝试在 java 中进行编码,以便 C# 代码可以对其进行解码。

任何帮助将不胜感激。

【问题讨论】:

  • @PeterDuniho 我不同意,这是一个很好的问题并且完全可以回答 - 在某种程度上,请参阅答案...

标签: java c# encryption


【解决方案1】:

问题在于 PasswordDeriveBytes 仅定义了前 20 个字节 - 在这种情况下,它是 PBKDF1(不是 2,正如您当前在 Java 代码中使用的那样)。多次调用getBytes 也可能会改变结果。一次或多次调用getBytes 或超过 20 个字节的算法是 Microsoft 专有的,似乎没有在任何地方描述。在 Mono 中,它甚至被描述为不可修复,因为它可能不安全。

我强烈建议使用 确实 实现 PBKDF2 的 RFC2898DeriveBytes。请注意仅将其用于 ASCII 输入,否则可能与 Java 实现不兼容。

唯一的其他选择是找出 Microsoft PasswordDeriveBytes 到 PBKDF1 的专有扩展(它只定义了高达 20 字节的散列大小的输出)。我在下面重新实现了 Mono 的版本。

多次向 Microsoft 请求更新此函数的 API 描述,但未产生任何结果。如果您的结果不同,您可能需要read this bug report


这是专有的 Microsoft 扩展。基本上它首先计算 PBKDF-1,但不包括最后一次哈希迭代,称为 HX。对于前 20 个字节,它只是执行另一个哈希,因此它符合 PBKDF1。下一个哈希值是计数器的 ASCII 表示,从 1 开始(因此首先转换为 "1",然后转换为 0x31),然后是 HX 的字节。

以下是从 Mono 代码进行的简约而直接的转换:

public class PasswordDeriveBytes {

    private final MessageDigest hash;
    private final byte[] initial;
    private final int iterations;

    private byte[] output;
    private int hashnumber = 0;
    private int position = 0;

    public PasswordDeriveBytes(String password, byte[] salt) {
        try {
            this.hash = MessageDigest.getInstance("SHA-1");
            this.initial = new byte[hash.getDigestLength()];
            this.hash.update(password.getBytes(UTF_8));
            this.hash.update(salt);
            this.hash.digest(this.initial, 0, this.initial.length);
            this.iterations = 100;
        } catch (NoSuchAlgorithmException | DigestException e) {
            throw new IllegalStateException(e);
        }
    }

    public byte[] getBytes(int cb) {
        if (cb < 1)
            throw new IndexOutOfBoundsException("cb");
        byte[] result = new byte[cb];
        int cpos = 0;
        // the initial hash (in reset) + at least one iteration
        int iter = Math.max(1, iterations - 1);
        // start with the PKCS5 key
        if (output == null) {
            // calculate the PKCS5 key
            output = initial;
            // generate new key material
            for (int i = 0; i < iter - 1; i++)
                output = hash.digest(output);
        }
        while (cpos < cb) {
            byte[] output2 = null;
            if (hashnumber == 0) {
                // last iteration on output
                output2 = hash.digest(output);
            } else if (hashnumber < 1000) {
                String n = String.valueOf(hashnumber);
                output2 = new byte[output.length + n.length()];
                for (int j = 0; j < n.length(); j++)
                    output2[j] = (byte) (n.charAt(j));
                System.arraycopy(output, 0, output2, n.length(), output.length);
                // don't update output
                output2 = hash.digest(output2);
            } else {
                throw new SecurityException();
            }
            int rem = output2.length - position;
            int l = Math.min(cb - cpos, rem);
            System.arraycopy(output2, position, result, cpos, l);
            cpos += l;
            position += l;
            while (position >= output2.length) {
                position -= output2.length;
                hashnumber++;
            }
        }
        return result;
    }
}

或者,更优化和可读性更高,只留下输出缓冲区和位置在调用之间进行更改:

public class PasswordDeriveBytes {

    private final MessageDigest hash;

    private final byte[] firstToLastDigest;
    private final byte[] outputBuffer;

    private int position = 0;

    public PasswordDeriveBytes(String password, byte[] salt) {
        try {
            this.hash = MessageDigest.getInstance("SHA-1");

            this.hash.update(password.getBytes(UTF_8));
            this.hash.update(salt);
            this.firstToLastDigest = this.hash.digest();

            final int iterations = 100;
            for (int i = 1; i < iterations - 1; i++) {
                hash.update(firstToLastDigest);
                hash.digest(firstToLastDigest, 0, firstToLastDigest.length);
            }

            this.outputBuffer = hash.digest(firstToLastDigest);

        } catch (NoSuchAlgorithmException | DigestException e) {
            throw new IllegalStateException("SHA-1 digest should always be available", e);
        }
    }

    public byte[] getBytes(int requested) {
        if (requested < 1) {
            throw new IllegalArgumentException(
                    "You should at least request 1 byte");
        }

        byte[] result = new byte[requested];

        int generated = 0;

        try {
            while (generated < requested) {
                final int outputOffset = position % outputBuffer.length;
                if (outputOffset == 0 && position != 0) {
                    final String counter = String.valueOf(position / outputBuffer.length);
                    hash.update(counter.getBytes(US_ASCII));
                    hash.update(firstToLastDigest);
                    hash.digest(outputBuffer, 0, outputBuffer.length);
                }

                final int left = outputBuffer.length - outputOffset;
                final int required = requested - generated;
                final int copy = Math.min(left, required);

                System.arraycopy(outputBuffer, outputOffset, result, generated, copy);

                generated += copy;
                position += copy;
            }
        } catch (final DigestException e) {
            throw new IllegalStateException(e);
        }
        return result;
    }
}

实际上,在安全方面并没有那么糟糕,因为字节被摘要彼此分开。所以重点拉伸是比较OK的。请注意,存在包含错误和重复字节的 Microsoft PasswordDeriveBytes 实现(请参阅上面的错误报告)。此处不再赘述。

用法:

private static final String PASSWORD = "46dkaKLKKJLjdkdk;akdjafj";

private static final byte[] SALT = { 0x26, 0x19, (byte) 0x81, 0x4E,
        (byte) 0xA0, 0x6D, (byte) 0x95, 0x34 };

public static void main(String[] args) throws Exception {
    final Cipher desEDE = Cipher.getInstance("DESede/CBC/PKCS5Padding");

    final PasswordDeriveBytes myPass = new PasswordDeriveBytes(PASSWORD, SALT);
    final SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");
    final byte[] key = myPass.getBytes(192 / Byte.SIZE);
    final SecretKey desEDEKey = kf.generateSecret(new DESedeKeySpec(key));

    final byte[] iv = myPass.getBytes(desEDE.getBlockSize());

    desEDE.init(Cipher.ENCRYPT_MODE, desEDEKey, new IvParameterSpec(iv));

    final byte[] ct = desEDE.doFinal("owlstead".getBytes(US_ASCII));
}

关于 Java 实现的附注:

  • 迭代次数太少,查看当前日期需要什么样的迭代次数
  • 密钥大小不正确,您应该创建 3 * 64 = 192 位而不是 196 位的密钥
  • 3DES 变老了,改用 AES

【讨论】:

  • 我使用 100 的原因是他们没有指定 PasswordderiveBytes 并且文档说默认值为 100。所以我试图在 java 中复制它。不确定这是否是最好的选择,安全方面,但此时我只是想让它工作。
  • 好的,没关系,但这是否意味着您也应该能够使用 PBKDF2?
  • 不,那是我想要做的,复制 c# 代码,它在 java 中使用 PBKDF1。唯一的事情是我需要在java中加密它,以便c#中的“set”代码可以解密它。至少这是目标。
  • 你能给我上面PasswordDeriveBytes函数的输出吗?在十六进制中,对于密钥和 IV?然后我可以尝试用 Java 重现结果(我很好奇)。我在这里使用 Linux,正如我已经指出的那样,Mono 不包含完整的实现。
  • 哦,还请阅读我的 cmets 答案here。很高兴您的密钥很大,因为 IV 实际上可能包含密钥中的字节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 2015-08-08
  • 2012-05-02
相关资源
最近更新 更多