首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的TripleDES包装器不工作

我的TripleDES包装器不工作
EN

Stack Overflow用户
提问于 2011-07-21 02:33:04
回答 1查看 552关注 0票数 0

下面是我的TripleDES包装器代码,它用于加密和解密整数:

代码语言:javascript
复制
public static class Crypto {

    private static Byte[]    _fixedIv = new Byte[] { /* 8 random bytes, const */ };

    private static TripleDES _tripleDes;
    private static Byte[]    _key;

    static Crypto() {

        _tripleDes = TripleDES.Create();
        _tripleDes.Mode = CipherMode.CFB;

        String key = ConfigurationManager.AppSettings["cryptoKeyId"];
        _key = Convert.FromBase64String( key );
    }

    /// <summary>Encrypts the specified integer using the configuration-stored key.</summary>
    public static String EncryptID(Int32 id) {

        Byte[] input = new Byte[8]; // 64-bit block size
        Byte[] inputLo = BitConverter.GetBytes( id );
        for(int i=0;i<inputLo.Length;i++) input[i] = inputLo[i];

        ICryptoTransform tr = _tripleDes.CreateEncryptor( _key, _fixedIv );

        Byte[] output = new Byte[8];
        tr.TransformBlock( input, 0, input.Length, output, 0 );

        return Convert.ToBase64String( output );
    }

    /// <summary>Decrypts the specified string (storing an integer) using the configuration-stored key.</summary>
    public static Int32 DecryptID(String s) {

        Byte[] ciphertext = Convert.FromBase64String(s);

        ICryptoTransform tr = _tripleDes.CreateDecryptor( _key, _fixedIv );

        Byte[] output = new Byte[8];
        tr.TransformBlock( ciphertext, 0, ciphertext.Length, output, 0 );

        Byte[] outputLo = new Byte[4] { output[0], output[1], output[2], output[3] };
        return BitConverter.ToInt32( outputLo, 0 );
    }

}

当我运行它时,我对EncryptID的每个输入都会得到确定性的结果,但是对DecryptID的每次调用都返回零。我一步一步进入代码,并指出'output‘数组的内容都是零( tr.TransformBlock返回零)。有人知道我做错了什么吗?

我试着给tr.TransformFinalBlock打电话,但得到了一个异常:

代码语言:javascript
复制
'tr.TransformFinalBlock( ciphertext, 0, ciphertext.Length )' threw an exception of type System.Security.Cryptography.CryptographicException' base {System.SystemException}: {"Bad Data.\r\n"}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-26 05:49:24

事实证明,对于单个块,我应该同时使用TransformFinalBlock进行加密和解密。

我还必须将algo.Padding设置为None,以确保将8字节的明文转换为8字节的密文。

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

https://stackoverflow.com/questions/6766718

复制
相关文章

相似问题

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