среда, 11 июня 2014 г.

How to break JCE crypto policy limit when using bouncycastle

    //this code allows to break limit if client jdk/jre has no unlimited policy files for JCE.
    //it should be run once. So this static section is always execute during the class loading process.
//this code is useful when working with Bouncycastle library.
    static {
        try {
            Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
            field.set(null, java.lang.Boolean.FALSE);
        } catch (Exception ex) {

or clojure variant of this function

(defn break-jce-policy-limit
  "This function breaks JCE crypto limits. Should be run once, primarily at the begining of the program
  to avoid JCE policy limit if JDK/JRE runtime has no installed files for break crypto limit. Returns nil."
  (safe (let [field (-> (Class/forName "javax.crypto.JceSecurity")
                      (.getDeclaredField "isRestricted"))]
          (.setAccessible field true)
          (.set field nil java.lang.Boolean/FALSE))))

(defmacro safe [bindings? & forms]
  "This macro is used to execute any function inside try-catch block."
  (let [bindings (if (and (even? (count bindings?)) (vector? bindings?))
                   bindings? nil)
        forms (if bindings forms (cons bindings? forms))
        except `(catch Exception e# e#
                  (println (.getMessage e#) e#))]
    (if bindings
      `(let ~bindings (try ~@forms ~except))
      `(try ~@forms ~except))))

Комментариев нет:

Отправить комментарий