近日一個java的項目,客戶要求項目中必須使用其提供的加密機制,扔給了兩個。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
?
? Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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)]…
?
? 設置強名稱:打開Visual Studio Command Prompt 輸入:sn -k TestComkey.snk 生成TestComkey.snk 文件
?
? 打開 Project--> Properties菜單 在Signing標簽中選中 Sign the assembly,選擇剛剛生成的強名稱文件TestComkey.snk
?
? 編譯程序Debug目錄中會生成 TestCom.dll 和TestCom.tlb
www.yzyedu.com
?
? 手工注冊Com方法:
?
? 打開Visual Studio Command Prompt進入Debug目錄,運行命令注冊:
?
? regasm TestCom.DLL /tlb:TestCom.tlb
www.jx-jf.com
?
? gacutil -i TestCom.DLL (執行這個命令需要TestCom.DLL 具有強名稱)
?
? 二、java 調用 Com
?
? 部署jacob
?
? 1、在開發環境中引入jacob.jar
?
? 2、拷貝jacob-1.15-M3-x86.dll 文件到 C:\Windows\System32目錄,如果是Web應用的話還需要拷貝到jdk1.5.0_16\bin目錄(jdk安裝目錄下的bin目錄)
?
? java調用代碼
?
? Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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();
?
? }
?
? }
?
? }
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
