         opts (function) hashing function to use
   Returns
         Result(Object):Signature object"
-  [^bytes digest priv-key {:keys [algorithm hash-algorithm]
-                           :or {algorithm :ecdsa hash-algorithm :sha256}}]
-  (let [hashed (hash digest :algorithm hash-algorithm)
-        signer (Signature/getInstance (name algorithm))]
-    (.initSign signer priv-key)
-    (.update signer hashed)
-    (.sign signer)))
+  [^bytes digest priv-key {:keys [algorithm curve hash-algorithm]
+                           :or {algorithm :ecdsa curve :secp256r1 hash-algorithm :sha256}}]
+  (let [signer (ECDSASigner.)
+        priv-params (-> curve name ECNamedCurveTable/getParameterSpec)
+        curve-n (.getN priv-params) ]
+    (->> (ECDomainParameters. (.getCurve priv-params) (.getG priv-params) curve-n)
+         (ECPrivateKeyParameters. (.getS ^BCECPrivateKey priv-key))
+         (.init signer true))
+    (let [out-stream (ByteArrayOutputStream.)
+          der-seq (DERSequenceGenerator. out-stream)
+          signature (prevent-malleability (.generateSignature signer
+                                                              (hash digest :algorithm hash-algorithm))
+                                          curve-n)]
+      (try 
+        (.addObject der-seq (ASN1Integer. ^BigInteger (aget signature 0)))
+        (.addObject der-seq (ASN1Integer. ^BigInteger (aget signature 1)))
+        (catch Exception e
+          (println "FIXME: log error?" e))
+        (finally (.close der-seq)))
+      
+      (.toByteArray out-stream))))
 
 ;;; verify
 (defn verify

;;;
(extend-type BCECPrivateKey
  IBCECKey
  (algorithm [this] (-> this .getAlgorithm keyword))
  (curve-spec [this] (keyword (.getName ^ECNamedCurveSpec (.getParams this))))
  (curve-params [this] (-> this .getParameters %curve-params))
  (%derive-key [this opts]
    (derive-bcec-key (curve-params this))))

(extend-type BCECPublicKey
  IBCECKey
  (algorithm [this] (-> this .getAlgorithm keyword))
  (curve-spec [this] (keyword (.getName ^ECNamedCurveSpec (.getParams this))))
  (curve-params [this] (-> this .getParameters %curve-params))
  (%derive-key [this opts]
    (derive-bcec-key (curve-params this))))

  [k cipher-text {:keys [algorithm] :as opts}]
  (%encrypt-or-decrypt k cipher-text (assoc opts :cipher-mode :decrypt)))

(defn- prevent-malleability
  [signature ^BigInteger curve-n]
  ;; Copy from Fabric SDK Java
  (let [cmp-val ^BigInteger (.divide curve-n (biginteger 2))
        s-val (aget signature 1)]
    (when (= (.compareTo ^BigInteger s-val cmp-val) 1)
      (aset signature 1 s-val))
    signature))

;;;sign
(defn sign
  "Sign the data.
