用java 编写一个凯撒加密和解密

用java 编写一个凯撒加密和解密,第1张

import java.util.Scanner

public class Caeser {

private String table// 定义密钥字母表

private int key// 定义密钥key

public Caeser(String table, int key) {

// 根据不同的字母表和不同的密钥生成一个新的凯撒算法,达到通用的目的

super()

this.table = table

this.key = key

}

public String encrypt(String from) {

//凯撒加密算法,传入明文字符串,返回一个密文字符串

String to = ""

for (int i = 0i <from.length()i++) {

to += table.charAt((table.indexOf(from.charAt(i))+key)%table.length())

}

return to

}

public static void main(String[] args) {

Caeser caeser = new Caeser("abcdefghijklmnopqrstuvwxyz", 3)

Scanner scanner = new Scanner(System.in)

System.out.println("请输入要加密的字符串")

String str =scanner.nextLine()//输入字符串 security

String result = caeser.encrypt(str)//调用加密方法进行加密

System.out.print(result)// 可得结果 vhfxulwb

}

}

不用类也是可以做的,不过看起来有些哆嗦,随便看一下吧,自己再改简单一点

using namespace std

const int N=20

void main()

{ int k

void encipher(char c[],int b)

void decipher(char c[],int b)

char plaintext[N]

cout<<"Please enter the keywards k(0<k<26):"<<endl

cin>>k

cout<<"Please enter the plaintext:"<<endl

cin>>plaintext

cout<<"the ciphertext is:"

encipher(plaintext,k)

cout<<"the plaintext is:"

decipher(plaintext,k)

}

void encipher(char c[],int b)

{

int i

int a[N]

for(i=0i<Ni++)

a[i]=c[i] //注:128~255是IBM-PC上专用的,ASCII代码中000-127是标准的,如果是z加20的就会超出128,故先赋给整型,然后再转换过来,

for(i=0a[i]!='\0'&&i<Ni++)

{

if((a[i]>='A'&&a[i]<='Z')||(a[i]>='a'&&a[i]<='z'))

{

a[i]=a[i]+b

if((a[i]>'Z'&&a[i]<='Z'+b)||(a[i]>'z'))

a[i]=a[i]-26}

}

for(i=0i<Ni++)

c[i]=a[i]

for(i=0i<Ni++)

cout<<c[i]

cout<<endl

}

void decipher(char c[],int b)

{

int i

for(i=0c[i]!='\0'&&i<Ni++)

{

if((c[i]>='A'&&c[i]<='Z')||(c[i]>='a'&&c[i]<='z'))

{

c[i]=c[i]-b

if((c[i]>='a'-b&&c[i]<'a')||c[i]<'A')

c[i]=c[i]+26}

}

for(i=0i<Ni++)

cout<<c[i]

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12023189.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存