凯撒加密解密

2018-09-10  本文已影响20人  Q大疯zi

学习到一个简单的加密算法,用Kotlin实现一下:

open class CaesarCrypt {
    /**
     * 凯撒加密算法
     */
    fun encrypt(str: String, key: Int): String {
        val result = with(StringBuffer()) {
            for (c in str.toCharArray()) {
                var result = c.toInt()
                result += key
                this.append(result.toChar())
            }
            this.toString()
        }
        return result
    }

    /**
     * 凯撒解密算法
     */
    fun decrypt(str: String, key: Int): String {
        val result = with(StringBuffer()) {
            for (c in str.toCharArray()) {
                var result = c.toInt()
                result -= key
                this.append(result.toChar())
            }
            this.toString()
        }
        return result
    }
}


fun main(args: Array<String>) {
    val text = "My house is perfect. By great good fortune I have found a housekeeper no less to my mind, a low-voiced, light-footed woman of discreet age, strong and deft enough to render me all the service I require, and not afraid of loneliness. She rises very early. By my breakfast-time there remains little to be done under the roof save dressing of meals. Very rarely do I hear even a clink of crockery; never the closing of a door or window. Oh, blessed silence! My house is perfect."
    val str = "hello world"
    val key = 15

    val encryptResult = CaesarCrypt().encrypt(str, key)
    println("加密算法结果:$encryptResult")
    val decryptResult = CaesarCrypt().decrypt(encryptResult, key)
    println("解密算法结果:$decryptResult")

    val textEncryptResult = CaesarCrypt().encrypt(text, key)
    //统计密文每个字符出现的个数
    val map = hashMapOf<Char, Int>()

    val toCharArray = textEncryptResult.toCharArray()
    toCharArray.forEach {
        println("字符数组:$it")
    }


    for (c in textEncryptResult.toCharArray()) {
        if (map.contains(c)) {
            map.put(c, (map.getValue(c) + 1))
        } else {
            map.put(c, 1)
        }

    }

    println("文章加密算法结果:$textEncryptResult")


    for ((k, v) in map) {
        println("含有字符:$k 个数$v ")
    }

    println("---------------")

    /**
     * 频度分析法,英文字符串中e字符出现的频率最高,所以先找解密后字符出现最高的字符
     * 分别为 / 其次是 t  ,根据/ - e 和 t - e的间距判断是-54 或者是 15,去解密
     * 测试后知道t为正确的,则key就为15
     * 
     *  //key -54  15
     *  //101  47  116
     */
    val textResult = CaesarCrypt().decrypt(textEncryptResult, 15)
    println("文章解密:$textResult")


}
上一篇下一篇

猜你喜欢

热点阅读