Javascript实现摩斯码加密解密

更新日期: 2021-12-07阅读: 1.2k标签: 密码

摩尔斯电码是一种时通时断的信号代码,通过不同的排列顺序来表达不同的英文字母、数字和标点符号,是由美国人萨缪尔·摩尔斯在1836年发明。每一个字符(字母或数字)对应不同的序列(由点和划组成)。

一般来说,任何一种能把书面字符用可变长度的信号表示的编码方式都可以称为摩尔斯电码。但现在这一术语只用来特指两种表示英语字母和符号的摩尔斯电码:美式摩尔斯电码和国际摩尔斯电码。下面内容仅针对国际摩尔斯电码。

摩斯码加密解密工具https://www.fly63.com/tool/morse/


字母、数字、标点、特殊字符与摩斯码对照表



除了上面的字符,也可以通过声音或光线亮度等媒介来传递摩斯密码信息,以声音为例,嘀代表(短声),哒代表(长声)。


摩斯码相关事件

前段时间被ISIS处决的日本人质后藤,在行刑过程中他的眨眼行为被摩斯电码专家解读为通过眨眼传递信息,翻译成文字为“不要救我,放弃我!”

在1912年的泰坦尼克号游轮沉没前,也曾发送SOS的求救信号。


Javascript实现摩斯码加密解析

使用字典来实现摩斯码与字符的对应关系,该字典也是基于对象来实现

低版本的IE无法通过下标来索引字符串进行遍历

IE在str.split(regExp) 中存在一个bug

var str = 'abb' ;
var r   = /b/g ;
alert(str.split('b'));   // chrome下提示 a,,  IE8下提示 a,,
alert(str.split(r));     // chrome下提示 a,,  IE8下提示 a

完整代码:

/*
* @author  liaoyu
* @created 2015-03-14
*/

var utils = utils || {};

utils.isArray = function(value) {
    return Object.prototype.toString.apply(value) === '[object Array]';
}

utils.trim = function(value) {
    return value.trim ? value.trim() : value.replace(/^\s+|\s+$|/g,'');
}

// 解决IE不兼容console问题
var console = console || {};
console.log = console.log || function(){};
console.error = console.error || function(){};

// 使用字典存储摩斯码对照关系
function Dictionary() {
    this.datasource = {};
    this.rdatasource = {};
}

Dictionary.prototype.add = function(keys, values) {
    if(typeof keys === 'undefined' || typeof values === 'undefined') {
        console.error('Illegal arguments');
        return ;
    }
    if(utils.isArray(keys) && utils.isArray(values)) {
        if(keys.length != values.length) {
            console.error('keys length not equals values length');
            return ;
        }
        for(var i = 0; i < keys.length; i++) {
            this.datasource[keys[i]] = values[i];
        }
        return ;
    }
    this.datasource[keys] = values;
}

Dictionary.prototype.reversal = function(){
    var tempData = this.datasource;
    for(var i in tempData) {
        if(tempData.hasOwnProperty(i)) {
            this.rdatasource[tempData[i]] = i;
        }
    }
}

Dictionary.prototype.showAll = function(values) {
    var count = 0;
    console.log('-----------morse code mapping-----------');
    for(var i in values) {
        if(values.hasOwnProperty(i)) {
            count++;
            console.log(i + '\t > ' + values[i]);
        }
    }
    console.log('total count: ' + count);
}

// morse code library
var morse = (function(global){
    var mcode = {},
        r_special = /\<\w+\>/g,
        r_find = /^\<(\w+)\>$/;

    // store datas mapping
    mcode.mdatas = (function(){
        var dictionaryDS = new Dictionary();
        // initial mappping
        dictionaryDS.add(
            [
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                '1','2','3','4','5','6','7','8','9','0',
                'AA','AR','AS','BK','BT','CT','SK','SOS',
                '.',':',',',';','?','=',"'",'/','!','-','_','"','(',')','$','&','@','+'
            ],
            [
                // letter
                '.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..',
                // number 
                '.----','..---','...--','....-','.....','-....','--...','---..','----.','-----',
                // special charactor
                '.-.-','.-.-.','.-...','-...-.-','-...-','-.-.-','...-.-','...---...',
                // punctuation
                '.-.-.-','---...','--..--','-.-.-.','..--..','-...-','.----.','-..-.','-.-.--','-....-','..--.-','.-..-.','-.--.','-.--.-','...-..-','.-...','.--.-.','.-.-.'
            ]
        );
        return dictionaryDS;
    }());
    
    // error flag
    mcode.error_flag = false;

    // 将字符串转换为摩斯码
    mcode.parse = function(values) {
        // console.log('input: ' + values);
        this.error_flag = false;

        var _datasource = this.mdatas.datasource,
            item = '',
            a_special = [],
            a_temp = [],
            a_value = [],
            count = 0,
            result = '';
        values = values.toUpperCase();
        a_special = values.match(r_special);
        a_temp = values.split(r_special);

        // 将用户输入的字符串转换成数组
        for(var i=0; i<a_temp.length; i++) {
            item = a_temp[i];
            if(item !== '') {
                // IE无法通过下标来索引字符串
                if(!item[0]){
                    item = item.split('');
                }
                for(var j=0; j<item.length; j++) {
                    a_value[count++] = item[j];
                }
            }

            // 当前字符串为<AS>形式,提取AS字符
            if(i !== a_temp.length - 1){
                a_value[count++] = a_special[i].match(r_find)[1];
            }
        }

        // 将解析数组形式的用户输入值
        for(var i=0; i<a_value.length; i++) {
            item = a_value[i];

            if(item === ' ') {
                result += '/ ';
            } else if(typeof _datasource[item] === 'undefined') {
                this.error_flag = true;
                // console.error('Invalid characters in input.')
                result += '? ';
            }else {
                result += _datasource[item] + ' ';
            }
        }
        return utils.trim(result);
    }

    //将摩斯码转换成字符串
    mcode.decode = function(values) {
        // console.log('input: ' + values);
        this.error_flag = false;

        this.mdatas.reversal();
        var _rdatasource = this.mdatas.rdatasource,
            a_input = values.split(' '),
            result = '',
            item = '',
            c_result = '';

        for(var i=0; i<a_input.length; i++) {
            item = a_input[i];
            if(item === '/') {
                result += ' ';
            }else {
                c_result = _rdatasource[item];
                if(typeof c_result === 'undefined') {
                    this.error_flag = true;
                    // console.error('Invalid characters in input.')
                    result += '?';
                } else {
                    if(c_result.length > 1){
                        result += '<' + c_result + '>';
                    } else {
                        result += c_result;
                    }
                }
            }
        }
        return result;
    }

    return mcode;
}(this));


链接: https://www.fly63.com/article/detial/10919

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!