java中的简单凯撒密码

Simple caesar cipher in java(java中的简单凯撒密码)
本文介绍了java中的简单凯撒密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

嘿,我正在使用公式 [x-> (x+shift-1) mod 127 + 1] 在 Java 中制作一个简单的凯撒密码,我希望我的加密文本具有除控制字符之外的 ASCII 字符(即从32-127).如何避免在加密文本中应用 0-31 的控制字符.谢谢.

Hey I'm making a simple caesar cipher in Java using the formula [x-> (x+shift-1) mod 127 + 1] I want to have my encrypted text to have the ASCII characters except the control characters(i.e from 32-127). How can I avoid the control characters from 0-31 applying in the encrypted text. Thank you.

推荐答案

这样的事情怎么样:

public String applyCaesar(String text, int shift)
{
    char[] chars = text.toCharArray();
    for (int i=0; i < text.length(); i++)
    {
        char c = chars[i];
        if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            if (x < 0) 
              x += 96; //java modulo can lead to negative values!
            chars[i] = (char) (x + 32);
        }
    }
    return new String(chars);
}

诚然,这将 127 视为非控制字符,但实际上并非如此……您可能希望对其进行调整以保持范围为 [32, 126].

Admittedly this treats 127 as a non-control character, which it isn't... you may wish to tweak it to keep the range as [32, 126].

这篇关于java中的简单凯撒密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)