GVKun编程网logo

asp.net – 当passwordFormat = Encrypted和decryption = AES时,从Membership迁移到Identity

23

在本文中,您将会了解到关于asp.net–当passwordFormat=Encrypted和decryption=AES时,从Membership迁移到Identity的新资讯,并给出一些关于.NE

在本文中,您将会了解到关于asp.net – 当passwordFormat = Encrypted和decryption = AES时,从Membership迁移到Identity的新资讯,并给出一些关于.NET DllImport 错误 EntryPointNotFoundException:将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#、active-directory – IdentityServer3 – 适用于ActiveDirectory:MembershipReboot / AspNetIdentity / UserService、AES encryption / decryption Objective-C category、AES Encryption and Decryption in Javascript的实用技巧。

本文目录一览:

asp.net – 当passwordFormat = Encrypted和decryption = AES时,从Membership迁移到Identity

asp.net – 当passwordFormat = Encrypted和decryption = AES时,从Membership迁移到Identity

最近我开始开发一个新的MVC应用程序,需要使用较旧的现有asp.net成员资格数据库并将其转换为新的(呃)身份系统.

如果您发现自己处于类似的情况,那么很可能您已经遇到了这个helpful post from microsoft,它为您提供了很好的指导和脚本,可以将数据库转换为新架构,包括密码.

为了处理两个系统之间密码散列/加密的差异,它们包括一个自定义密码哈希,sqlPasswordHasher,它解析密码字段(已合并到Password | PasswordFormat | Salt)并尝试复制sqlMembershipProvider中的逻辑将传入的密码与存储的版本进行比较.

然而,正如我(以及该帖子上的另一位评论者)所注意到的,他们提供的这个方便的哈希不处理加密密码(尽管他们在帖子中使用的混淆语言似乎表明它确实如此).它似乎应该是,考虑到它们确实将密码格式带入数据库,但奇怪的是代码不使用它,而是

int passwordformat = 1;

这是用于散列密码.我需要的是能够使用System.Web / MachineKey配置元素的decryptionKey处理我的场景的加密密码.

如果你也处于这样的困境,并且正在使用AES算法(如machineKey的解密属性中所定义的那样),那么下面的答案应该得到解决.

解决方法

首先,让我们快速谈谈sqlMembershipProvider在幕后做的事情.提供程序通过将两者连接在一起,将转换为byte []的salt与编码为unicode字节数组的密码组合成一个更大的字节数组.非常直截了当.然后它通过抽象(MembershipAdapter)将其传递给MachineKeySection,在那里完成实际工作.

关于该切换的重要部分是它指示MachineKeySection使用空IV(初始化向量)并且还不执行签名.那个空的IV是真正的关键,因为machineKey元素没有IV属性,所以如果你已经摸不着头脑,想知道提供者如何处理这个方面,那就是这样.一旦你知道(从挖掘源代码)然后你可以提取MachineKeySection代码中的加密代码,并将其与成员资格提供程序的代码结合起来,以获得更完整的哈希.完整来源:

public class sqlPasswordHasher : PasswordHasher
{
    public override string HashPassword(string password)
    {
        return base.HashPassword(password);
    }

    public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword,string providedPassword)
    {
        string[] passwordProperties = hashedPassword.Split('|');
        if (passwordProperties.Length != 3)
        {
            return base.VerifyHashedPassword(hashedPassword,providedPassword);
        }
        else
        {
            string passwordHash = passwordProperties[0];
            int passwordformat = int.Parse(passwordProperties[1]);
            string salt = passwordProperties[2];

            if (String.Equals(EncryptPassword(providedPassword,passwordformat,salt),passwordHash,StringComparison.CurrentCultureIgnoreCase))
            {
                return PasswordVerificationResult.SuccessRehashNeeded;
            }
            else
            {
                return PasswordVerificationResult.Failed;
            }

        }
    }

    //This is copied from the existing sql providers and is provided only for back-compat.
    private string EncryptPassword(string pass,int passwordFormat,string salt)
    {
        if (passwordFormat == 0) // MembershipPasswordFormat.Clear
            return pass;

        byte[] bIn = Encoding.Unicode.GetBytes(pass);
        byte[] bSalt = Convert.FromBase64String(salt);
        byte[] bRet = null;

        if (passwordFormat == 1)
        { // MembershipPasswordFormat.Hashed 
            HashAlgorithm hm = HashAlgorithm.Create("SHA1");
            if (hm is KeyedHashAlgorithm)
            {
                KeyedHashAlgorithm kha = (KeyedHashAlgorithm)hm;
                if (kha.Key.Length == bSalt.Length)
                {
                    kha.Key = bSalt;
                }
                else if (kha.Key.Length < bSalt.Length)
                {
                    byte[] bKey = new byte[kha.Key.Length];
                    Buffer.Blockcopy(bSalt,bKey,bKey.Length);
                    kha.Key = bKey;
                }
                else
                {
                    byte[] bKey = new byte[kha.Key.Length];
                    for (int iter = 0; iter < bKey.Length;)
                    {
                        int len = Math.Min(bSalt.Length,bKey.Length - iter);
                        Buffer.Blockcopy(bSalt,iter,len);
                        iter += len;
                    }
                    kha.Key = bKey;
                }
                bRet = kha.ComputeHash(bIn);
            }
            else
            {
                byte[] bAll = new byte[bSalt.Length + bIn.Length];
                Buffer.Blockcopy(bSalt,bAll,bSalt.Length);
                Buffer.Blockcopy(bIn,bSalt.Length,bIn.Length);
                bRet = hm.ComputeHash(bAll);
            }
        }
        else //MembershipPasswordFormat.Encrypted,aka 2
        {               
            byte[] bEncrypt = new byte[bSalt.Length + bIn.Length];
            Buffer.Blockcopy(bSalt,bEncrypt,bSalt.Length);
            Buffer.Blockcopy(bIn,bIn.Length);

            // distilled from MachineKeyConfigSection EncryptOrDecryptData function,assuming AES algo and paswordCompatMode=Framework20 (the default)
            MemoryStream stream = new MemoryStream();
            var aes = new AesCryptoServiceProvider();
            aes.Key = HexStringToByteArray(MachineKey.DecryptionKey);
            aes.GenerateIV();
            aes.IV = new byte[aes.IV.Length];
            ICryptoTransform transform = aes.CreateEncryptor(); 

            CryptoStream stream2 = new CryptoStream(stream,transform,CryptoStreamMode.Write);

            stream2.Write(bEncrypt,bEncrypt.Length);

            stream2.FlushFinalBlock();
            bRet = stream.ToArray();
            stream2.Close();
            //               
        }

        return Convert.ToBase64String(bRet);
    }

    public static byte[] HexStringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i,2),16);
        return bytes;
    }

    private static MachineKeySection MachineKey
    {
        get
        {
            //Get encryption and decryption key information from the configuration.
            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            return cfg.GetSection("system.web/machineKey") as MachineKeySection;
        }
    }


}

如果您有不同的算法,那么步骤将非常接近相同,但您可能希望首先深入了解MachineKeySection的源代码,并仔细了解它们如何初始化事物.快乐的编码!

.NET DllImport 错误 EntryPointNotFoundException:将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#

.NET DllImport 错误 EntryPointNotFoundException:将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#

如何解决.NET DllImport 错误 EntryPointNotFoundException:将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#?

我正在开发一个 .NET 5 项目,以使用 PInvoke、类型编组和 DllImportAttribute 将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#。尝试调用此 C++ 函数时

aws_cryptosdk_keyring *Build(const Aws::String &generator_key_id,const Aws::Vector<Aws::String> &additional_key_ids = {}) const;

使用

[DllImport("aws-encryption-sdk-cpp.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern aws_cryptosdk_keyring Build(string generator_key_id,string[] additional_key_ids = null);

我收到此错误

System.EntryPointNotFoundException:无法在 DLL“aws-encryption-sdk-cpp.dll”中找到名为“Build”的入口点。

这个函数的dll签名是

?Build@Builder@KmsKeyring@Cryptosdk@Aws@@QEBAPEAUaws_cryptosdk_keyring@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV?$vector @V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V ?$allocator@D@2@@std@@@2@@7@@Z

到目前为止,我尝试过的所有入口点都没有成功。有人有什么想法吗?

解决方法

扩展@jwezorek 的评论,C# 不知道如何调用 C++(类)函数,只会调用 C 函数。造成这种情况的原因有很多,但我不会在这里讨论。

您需要(在 C++ 中)创建一个包装器,将每个 C++ 调用转换为“扁平化”的 C 调用。例如:

extern "C" void *createClass() {
  return (void*) new myClass();
}

extern "C" void destroyClass(void* self) {
  delete (myClass*) self;
}

extern "C" int callFunction1(void* self,int x,int y) {
  return ((myClass*) self)->function1(x,y);
}

您需要为每个类函数(加上构造函数和析构函数)编写一个函数。然后编译,将其链接到原始 C++ DLL 的库。然后在 C# 中,编写一个包装器来调用扁平化的类:

public class myClass : IDisposable {
  [DllImport("myFlattenedDll",EntryPoint="createClass")]
  public static extern IntPtr createClass();
  [DllImport("myFlattenedDll",EntryPoint="destroyClass")]
  public static extern void destroyClass(IntPtr self);
  [DllImport("myFlattenedDll",EntryPoint="callFunction1")]
  public static extern int callFunction1(IntPtr self,int y);

  private IntPtr self;

  public myClass() {
    self = createClass();
  }

  ~myClass() {
    Dispose();
  }

  public virtual void Dispose() {
    lock (this) {
      destroyClass(self);
      GC.SuppressFinalize(this);
    }
  }

  public int callFunction1(int x,int y) {
    return callFunction1(self,x,y);
  }
}

您还应该研究一个名为 SWIG 的工具,它可以为您自动化大量的包装器编码。

active-directory – IdentityServer3 – 适用于ActiveDirectory:MembershipReboot / AspNetIdentity / UserService

active-directory – IdentityServer3 – 适用于ActiveDirectory:MembershipReboot / AspNetIdentity / UserService

我希望以下问题有道理:

>我在ActiveDirectory中管理我的用户.
>我通过IdentityServer3验证它们.
>我通过用户所在的AD组授权API(充当安全角色).

我应该如何设置IdentityServer3:

>我必须使用自己的自定义UserService来访问ActiveDirectory吗?
>是否取代了MembershipReboot / AspNetIdentity支持(或者我误解了UserService是什么)?
>或者我应该使用IdentityServer3中的MembershipReboot / AspNetIdentity包之一,并以某种方式自定义它们以映射到ActiveDirectory(如果是,如何)?

解决方法

似乎没有“映射”,不应该是从AD到成员资格重新启动或异常或更新的身份重启用户存储的映射.原因似乎很简单:mr和aspid或ir都是以持久方式(某种数据库或存储库)存储用户信息的方法,这已在AD中完成.

用户服务就足够了.在客户端调用“装饰”“授权”属性或从OP返回后,它会导致填充ASP Identity对象,并使中间件按预期工作,正确且自动地调用用户身份验证和用户或资源授权(OpenID-Connect提供程序)或来自单独的授权或资源提供程序的安全调用.

答案更新:现在在IdentityServer4中,不推荐使用UserService,而是使用IResourceOwnerPasswordValidator.

请参阅此处查看工作代码和详细说明,在接受后的答案中(请将其投票)
IdentityServer4 register UserService and get users from database in asp.net core

AES encryption / decryption Objective-C category

AES encryption / decryption Objective-C category

NSData+NSData_AES.h

//
//  NSData+NSData_AES.h
//  CSVContactDemo
//
//  Created by Michael on 14-7-23.
//  Copyright (c) 2014年 Michael. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSData (Encryption)

- (NSData *)AES256EncryptWithKey:(NSString *)key;   //加密
- (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密

@end

NSData+NSData_AES.m

//
//  NSData+NSData_AES.m
//  CSVContactDemo
//
//  Created by Michael on 14-7-23.
//  Copyright (c) 2014年 Michael. All rights reserved.
//


#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (Encryption)

- (NSData *)AES256EncryptWithKey:(NSString *)key {//加密
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}


- (NSData *)AES256DecryptWithKey:(NSString *)key {//解密
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
}

@end


AES Encryption and Decryption in Javascript

AES Encryption and Decryption in Javascript

How to use


  • Download aes.js

    Download

  • Javascript code

<script type="text/javascript">
    var data = ''1234567890'';
    var AES = {
        key: CryptoJS.enc.Utf8.parse(''ASDFGHJKLZXCVBNM''),
        iv: CryptoJS.enc.Utf8.parse(''ASDFGHJKLZXCVBNM''),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        /*encryption*/
        encrypt: function(data) {
            data = CryptoJS.AES.encrypt(datathis.key, {
                iv: this.iv,
                mode: this.mode,
                padding: this.padding
            });
            return data.ciphertext.toString(CryptoJS.enc.Base64);
        },
        /*decryption*/
        decrypt: function(data) {
            data = CryptoJS.AES.decrypt(datathis.key, {
                iv: this.iv,
                mode: this.mode,
                padding: this.padding
            });
            return data.toString(CryptoJS.enc.Utf8);
        }
    };
    //encryption
    var endata = AES.encrypt(data);
    //descyption
    var dedata = AES.decrypt(endata);
    console.log(''AES endata:'', endata);
    console.log(''AES dedata:'', dedata);
</script>
  • Testing result

   

今天的关于asp.net – 当passwordFormat = Encrypted和decryption = AES时,从Membership迁移到Identity的分享已经结束,谢谢您的关注,如果想了解更多关于.NET DllImport 错误 EntryPointNotFoundException:将 AWS-Encryption-SDK 从 C 和 C++ 绑定到 C#、active-directory – IdentityServer3 – 适用于ActiveDirectory:MembershipReboot / AspNetIdentity / UserService、AES encryption / decryption Objective-C category、AES Encryption and Decryption in Javascript的相关知识,请在本站进行查询。

本文标签: