2025-02-10

項目必須使用其提供的加密機制,扔給瞭兩個.net寫的DLL。網絡上搜瞭一圈也沒找到啥東西,甚至看到人揚言此事絕無可能。鬱悶當中考慮瞭一個思路。用C#做一個Com,調用客戶提供的DLL 實現加密解密的方法,然後提供給java使用。經過一番搗騰,最後證實可行。

環境與工具:
1、.net framework 3.5  C#
2、java jdk1.5,   Tomcat 5.5
3、jacob-1.15-M3

實現例子:
一、C# 制作Com組件
新建一個Class 項目,取名TestCom
 \代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace TestCom
{
    [Guid(“E9BCF867-CD81-40d0-9591-ED28D1ED2B53”)]
    public interface IEncrypt
    {
        [DispId(1)]
         string GetEncrypt(string str,string str2);
    }
    [Guid(“33A6E58D-E1F5-4b53-B2E2-03B9F8BA2FAD”), ClassInterface(ClassInterfaceType.None)]
    public class Encrypt:IEncrypt
    {
        public Encrypt(){}

        public string GetEncrypt(string str,string str2)
        {
           
             return  “測試 | ” str “|” str2;
        }
    }
}
打開 Project–>  Properties菜單  在Application標簽中打開 Assembly Information 將Make assembly Com-Visible一項選中。再切換到Build標簽將 Register for COM interop一項選中。
 Guid的生成:打開Visual Studio Command Prompt 輸入guidgen 命令調出工具。類型選擇Registry Format,點擊New Guid,然後COPY出來。
[DispId(1)]為函數的標識。如果有多個函數可相應的在函數前面加[DispId(2)], [DispId(3)]…
編譯程序Debug目錄中會生成 TestCom.dll 和TestCom.tlb
手工註冊Com方法:
打開Visual Studio Command Prompt進入Debug目錄,運行命令註冊:regasm TestCom.DLL /tlb:TestCom.tlb

二、java 調用 Com
部署jacob
1、在開發環境中引入jacob.jar
2、拷貝jacob-1.15-M3-x86.dll 文件到 C:WindowsSystem32目錄,如果是Web應用的話還需要拷貝到jdk1.5.0_16in目錄(jdk安裝目錄下的bin目錄)

java調用代碼
 \代碼
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
            ActiveXComponent dotnetCom = null;
            dotnetCom = new ActiveXComponent(“TestCom.Encrypt”);
            Variant var = Dispatch.call(dotnetCom,”GetEncrypt”,”哥是第一個參數”,”哥是第二個參數”);
            String str  = var.toString(); //返回值
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    }

}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *