[問題] 關於3DES key與密文相反的問題?

看板java作者 (胡小揚)時間11年前 (2012/10/05 14:40), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串1/1
各位好 我要做的是一個使用3DES加解密的程式 範例是 DATA: 00 00 00 00 00 00 00 00 KEYA: 40 42 44 46 48 4A 7E 00 KEYB: 00 7E 60 62 64 66 68 6A 算出來為 8C 7F 46 D7 6C E0 12 66 可是我寫出來的程式演算法應該是沒有問題 但key必須倒著輸入才會算出正確的值 且正確的值也是倒過來的XD 以下是程式碼 import java.security.Key; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; public class BcTest { static void test() throws Exception { byte[] data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] key1 = new byte[] { 0x00, 0x7E, (byte) 0x4A, (byte) 0x48, (byte) 0x46, (byte) 0x44, (byte) 0x42, (byte) 0x40 }; byte[] key2 = new byte[] { (byte) 0x6A, (byte) 0x68, (byte) 0x66, (byte) 0x64, (byte) 0x62, (byte) 0x60, 0x7E, 0x00 }; // 3DES ciphertext = EK3(DK2(EK1(plaintext))) byte[] crypt = encrypt(decrypt(encrypt(data, key1), key2), key1); // 3DES plaintext = DK1(EK2(DK3(ciphertext))) byte[] plain = decrypt(encrypt(decrypt(crypt, key1), key2), key1); System.out.println(" key1: " + ByteUtil.bytes2HexSpace(key1) + "\n key2: " + ByteUtil.bytes2HexSpace(key2)); System.out.println(" data: " + ByteUtil.bytes2HexSpace(data)); System.out.println("crypt: " + ByteUtil.bytes2HexSpace(crypt)); System.out.println("plain: " + ByteUtil.bytes2HexSpace(plain)); } public static void main(String[] args) throws Exception { test(); } public static byte[] decrypt(byte[] crypt, byte[] key) throws Exception { Key k = toKey(key); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, k); return cipher.doFinal(crypt); } public static byte[] encrypt(byte[] data, byte[] key) throws Exception { Key k = toKey(key); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, k); return cipher.doFinal(data); } public static SecretKey toKey(byte[] key) throws Exception { KeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); return keyFactory.generateSecret(dks); } } class ByteUtil { private static final char HEX[] = "0123456789ABCFEF".toCharArray(); public static String bytes2HexSpace(byte bys[]) { char chs[] = new char[(bys.length * 2 + bys.length) - 1]; int i = 0; int offset = 0; for (; i < bys.length; i++) { if (i > 0) chs[offset++] = ' '; chs[offset++] = HEX[bys[i] >> 4 & 15]; chs[offset++] = HEX[bys[i] & 15]; } return new String(chs); } } 我個人是覺得 LSB MSB的問題!? 麻煩各位解答了 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 192.192.114.225

10/08 21:44, , 1F
關於作業文不排版的問題
10/08 21:44, 1F

10/08 21:46, , 2F
請原PO幫忙回答
10/08 21:46, 2F
文章代碼(AID): #1GRe3j3C (java)