字节集合在clojure上串起来

时间:2011-08-24 20:11:47

标签: string clojure encryption

以下代码

(defn caesar-block-cypher
  "Computes the caesar block cypher for the given text with the k key. Returns an array of bytes"
  [k text]
  (let [byte-string (.getBytes text)]
    (loop [return-byte-array [] byte-string byte-string]
      (if (= '() byte-string)
        return-byte-array
        (recur
          (conj return-byte-array (byte (+ k (first byte-string))))
          (rest byte-string))))))

在处理带有密钥k的caesar密码后,返回一个字节数组。我想将字节数组转换回字符串或直接在字符串上执行密码,但(new String return-byte-array)不起作用。有什么建议吗?


编辑:感谢您的回复。我在一个更实用的风格(实际上有效)上重新编写了这个:

(defn caesar-block-cypher
  "Computes the caesar block cypher for the given text with the k key."
  [k text & more]
    (let [byte-string (.getBytes (apply str text (map str more)))]
      (apply str (map #(char (mod (+ (int %) k) 0x100)) byte-string))))

4 个答案:

答案 0 :(得分:23)

(let [byte-array (caesar-block-cypher 1 "Hello, world!")]
    (apply str (map char byte-array)))

答案 1 :(得分:16)

使用java的String构造函数快速创建字符串,

(let [b (caesar-block-cypher 1 "Hello World")]
  (String. b))

答案 2 :(得分:6)

AFAIK凯撒密码只是改变字符为什么要处理字节,


(let [s "Attack"
      k 1
      encoded (map #(char (+ (int %) k)) s)
      decoded (map #(char (- (int %) k)) encoded)]
  (apply str decoded))

答案 3 :(得分:2)

您可以使用slurp,它也适用于字节数组:

来自https://clojuredocs.org/clojure.core/slurp#example-588dd268e4b01f4add58fe33

;; you can read bytes also

(def arr-bytes (into-array Byte/TYPE (range 128)))
(slurp arr-bytes)