【问题标题】:Initialization vector is not supported in gwtgwt 不支持初始化向量
【发布时间】:2017-08-24 14:47:33
【问题描述】:

我正在尝试在客户端使用初始化向量和密钥进行解密,但 GWT 无法识别它,我添加了加密库但仍然不受支持。如何使用初始化向量使加密和解密更安全。

在服务器端我能够加密但在客户端我无法解密.. GWT 不支持 KeyGenerator 和 IvParameterSpec

private String encryptDES(String sessionKey) throws Exception {
    KeyGenerator keygenerator = KeyGenerator.getInstance("DESede");
    SecretKey myKey = keygenerator.generateKey();
    SecureRandom sr = new SecureRandom(); 
    byte [] iv = new byte[8]; 
    sr.nextBytes(iv); 
    IvParameterSpec IV = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, myKey, IV);
    String encrypted = Base64.encode(cipher.doFinal(sessionKey.getBytes()));
    return encrypted;
}

请帮我解决一下

【问题讨论】:

    标签: java encryption gwt


    【解决方案1】:

    围绕cryptoJS编写一个包装器 应少于 100 行代码。

    从 crypto.js 注入例如 aes

    String url = GWT.getModuleBaseForStaticFiles() + "js/aes.js";
    ScriptInjector.fromUrl(url).setWindow(ScriptInjector.TOP_WINDOW).inject();
    

    加密

    /**
     * Encrypt the given String with the given key.
     *
     * @param s The String to encrypt
     * @param cipher The cipher
     * @return The encrypted String
     */
     public static native String encrypt(String s, String cipher)
     /*-{
        var key = $wnd.CryptoJS.enc.Utf8.parse(cipher);
        var iv = $wnd.CryptoJS.enc.Utf8.parse(cipher);
    
        var encrypted = $wnd.CryptoJS.AES.encrypt($wnd.CryptoJS.enc.Utf8.parse(s), key,
        {
           keySize: 128 / 8,
           iv: iv,
           mode: $wnd.CryptoJS.mode.CBC,
           padding: $wnd.CryptoJS.pad.Pkcs7
        });
    
        return encrypted;
     }-*/;
    

    解密

    /**
     * Decrypt the given String with the given key.
     *
     * @param s The String to decrypt
     * @param cipher The key
     * @return The decrypted String
     */
    public static native String decrypt(String s, String cipher)
    /*-{
       var key = $wnd.CryptoJS.enc.Utf8.parse(cipher);
       var iv = $wnd.CryptoJS.enc.Utf8.parse(cipher);
    
       var decrypted = $wnd.CryptoJS.AES.decrypt(s, key,
       {
          keySize: 128 / 8,
          iv: iv,
          mode: $wnd.CryptoJS.mode.CBC,
          padding: $wnd.CryptoJS.pad.Pkcs7
       });
    
       return decrypted.toString($wnd.CryptoJS.enc.Utf8);
    }-*/;
    

    【讨论】:

    • 我尝试使用 JSNI 但没有成功。我已经有了 TripleDes 实现,但使用了硬编码的键值。现在我希望密钥更安全,所以它必须是随机生成的。我厌倦了一些approch 但没有任何工作..我无法在 Internet 上找到任何解决方案来随机生成 GWT 支持的密钥..请提供任何示例
    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2011-05-23
    • 2012-09-25
    • 1970-01-01
    相关资源
    最近更新 更多