我正在尝试创建一个 .NET DLL,以便我可以在我的非 .NET 应用程序中使用加密函数。
到目前为止,我已经使用这段代码创建了一个类库:
namespace AESEncryption
{
public class EncryptDecrypt
{
private static readonly byte[] optionalEntropy = { 0x21, 0x05, 0x07, 0x08, 0x27, 0x02, 0x23, 0x36, 0x45, 0x50 };
public interface IEncrypt
{
string Encrypt(string data, string filePath);
};
public class EncryptDecryptInt:IEncrypt
{
public string Encrypt(string data, string filePath)
{
byte[] plainKey;
try
{
// Read in the secret key from our cipher key store
byte[] cipher = File.ReadAllBytes(filePath);
plainKey = ProtectedData.Unprotect(cipher, optionalEntropy, DataProtectionScope.CurrentUser);
// Convert our plaintext data into a byte array
byte[] plainTextBytes = Encoding.ASCII.GetBytes(data);
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Mode = CipherMode.CBC;
alg.Key = plainKey;
alg.IV = optionalEntropy;
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plainTextBytes, 0, plainTextBytes.Length);
cs.Close();
byte[] encryptedData = ms.ToArray();
return Convert.ToString(encryptedData);
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
}
在我的 VC++ 应用程序中,我使用 #import 指令导入从 DLL 创建的 TLB 文件,但唯一可用的函数是 _AESEncryption 和 LIB_AES 等
我没有看到接口(interface)或函数 Encrypt。
当我尝试实例化以便调用我的 VC++ 程序中的函数时,我使用了这段代码并得到了以下错误:
HRESULT hr = CoInitialize(NULL);
IEncryptPtr pIEncrypt(__uuidof(EncryptDecryptInt));
错误 C2065:“IEncryptPtr”:未声明的标识符
错误 C2146:语法错误:缺少“;”在标识符“pIEncrypt”之前
最佳答案
您似乎没有将接口(interface)标记为通过 COM 可见。我希望看到类似的内容:
namespace AESEncryption
{
[Guid("[a new guid for the interface]")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEncrypt {
string Encrypt(string data, string filePath);
}
[Guid("[a new guid for the class]")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class EncryptDecryptInt : IEncrypt
{
public string Encrypt(string data, string filePath)
{
// etc.
}
}
}
关于c# - 尝试创建与非 .NET 应用程序一起使用的 .NET DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2592653/