首页 > 解决方案 > Triple DES 的实现在 CryptoJS 和 gwt-crypto 中输出不同的结果

问题描述

我将CryptoJS库用于 Angular 2+ 项目,我将gwt-crypto库用于 Java 项目。根据这篇文章,可以轻松实现三重DES,所以我这样做了:

import com.googlecode.gwt.crypto.bouncycastle.DataLengthException;
import com.googlecode.gwt.crypto.bouncycastle.InvalidCipherTextException;
import com.googlecode.gwt.crypto.client.TripleDesCipher;
public class CryptoKit {
    private static final String LOCAL_KEY = "exampleofsecretkey4myapp";
    public static String encryptMessage(String textToEncrypt) {
        byte[] key = LOCAL_KEY.getBytes();
        TripleDesCipher cipher = new TripleDesCipher();
        cipher.setKey(key);
        String textEncrypted = "";
        try {
            textEncrypted = cipher.encrypt(String.valueOf(textToEncrypt));
        } catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) {
            e.printStackTrace();
        }
        return textEncrypted;
    }
    public static String decryptMessage(String textToDecrypt) {
        byte[] key = LOCAL_KEY.getBytes();
        TripleDesCipher cipher = new TripleDesCipher();
        cipher.setKey(key);
        String textDecrypted = "";
        try {
            textDecrypted = cipher.decrypt(textToDecrypt);
        } catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) {
            e.printStackTrace();
        }
        return textDecrypted;
    }
}

当我想与我的 Angular 应用程序通信时,我尝试使用 CryptoJS 进行相同的练习,例如:

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable({
  providedIn: 'root'
})
export class VdCryptoService {
  private static localKey: string = 'exampleofsecretkey4myapp';
  encryptMessage(message: string): string {
    return CryptoJS.TripleDES.encrypt(message, this.localKey).toString();
  }
  decryptMessage(message: string): string {
    return CryptoJS.TripleDES.decrypt(message, this.localKey).toString(CryptoJS.enc.Utf8);
  }
}

但是当我测试我的两个应用程序时,它们会输出不同的加密结果。例如,如果我使用“示例消息”作为输入进行测试,我会得到:

CryptoJS: U2FsdGVkX1/l7hDE9US+MQFcmBw3u2HWN45H3c8shsk=

gwt-crypto: ac5f6601d994bb6a9b7ea304a1523c99

作为一个有趣的事实,两个应用程序都可以正确加密和解​​密,但它们输出不同的加密,我不知道如何解决这个问题,以便它们之间进行通信。有人可以帮助我吗?,也许我需要我不知道的程序,或者我做错了。

谢谢你。

标签: angularencryptiongwtcryptojs

解决方案


推荐阅读