Java中3DES加密解密與其他語言(如C/C++)通信


國內私募機構九鼎控股打造APP,來就送 20元現金領取地址: http://jdb.jiudingcapital.com/phone.html
內部邀請碼: C8E245J (不寫邀請碼,沒有現金送)
國內私募機構九鼎控股打造,九鼎投資是在全國股份轉讓系統掛牌的公眾公司,股票代碼為430719,為“中國PE第一股”,市值超1000億元。 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

3DES(即Triple DES)是DES向AES過渡的加密算法(1999年,NIST將3-DES指定為過渡的加密標准),是DES的一個更安全的變形。它以DES為基本模塊,通過組合分組方法設計出分組加密算法,

其具體實現如下:

設Ek()和Dk()代表DES算法的加密和解密過程,K代表DES算法使用的密鑰,P代表明文,C代表密表,這樣,

3DES加密過程為:C=Ek3(Dk2(Ek1(P)))

3DES解密過程為:P=Dk1((EK2(Dk3(C)))


       K1、K2、K3決定了算法的安全性,若三個密鑰互不相同,本質上就相當於用一個長為168位的密鑰進行加密。多年來,它在對付強力攻擊時是比較安全的。若數據對安全性要求不那么高,K1可以等於K3。在這種情況下,密鑰的有效長度為112位。當然,只用Java語言編寫程序進行3DES的加密解密不用考慮任何問題,因為加密和解密是逆向過程,用的model和padding都是相同的,考慮到Java與其他語言通信時,就必須兩種語言的model和padding是相同的才可以。

從一下的說明可以看出這一點:

 

使用cipher可以很容易的實現3des加密,但是跟其他平台開發的3des加密對接來說,通常會有一些問題。基本的程序如下: 

public static byte[] desEncrypt(String message, String key) throws Exception { 
Cipher cipher = Cipher.getInstance("DESede"); 

DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); 
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); 
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 
cipher.init(Cipher.ENCRYPT_MODE, secretKey); 

return cipher.doFinal(message.getBytes("UTF-8")); 

 

 

我們跟其他平台對接發現對同樣輸入加密以后結果不同,看看jdk的文檔,有如下描述: 

A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output.
A transformation is of the form:
•"algorithm/mode/padding" or •"algorithm"
(in the latter case, provider-specific default values for the mode and padding scheme are used).

根據前面的代碼,我們已經選擇了正確的算法,那么加密不同的原因應該就是mode和padding了。 

he SunJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES, DES-EDE and Blowfish ciphers. This means that in the case of the SunJCE provider,

Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding"); 

 

and

Cipher c1 = Cipher.getInstance("DES"); 

 

are equivalent statements.

 

對於其他語言開發的3des,一定要采用相同的mode和padding才能保證通信。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM