JAVA實現(xiàn)caesar凱撒加密算法
public class Caesar {
public static final String SOURCE = "abcdefghijklmnopqrstuvwxyz";
public static final int LEN = SOURCE.length();
/**
* @param args
*/
public static void main(String[] args) {
String result = caesarEncryption("newyork");
System.out.println("encryption result:" + result);
System.out.println("decryption result:" + caesarDecryption(result));
}
//Encryption
public static String caesarEncryption(String s) {
StringBuilder sb = new StringBuilder();
if (s == null || s.length() < 1) {
System.out.println("you Input nothing.");
return null;
}
if (!isAlp(s)) {
System.out.println("input ABC... only");
return null;
}
s = s.toLowerCase();
int len = s.length();
for (int j = 0; j < len; j++) {
char c = s.charAt(j);
int a = SOURCE.indexOf(c);
if (a == LEN -1) a = -1;
if (a == LEN -2) a = -2;
if (a == LEN - 3) a = -3;
sb.append(SOURCE.charAt(a + 3));
}
return sb.toString();
}
//Decryption
public static String caesarDecryption(String s) {
StringBuilder sb = new StringBuilder();
if (s == null || s.length() < 1) {
System.out.println("you Input nothing.");
return null;
}
if (!isAlp(s)) {
System.out.println("input ABC... only");
return null;
}
s = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int a = SOURCE.indexOf(c);
if (a == 2) a = LEN + 2;
if (a == 1) a = LEN + 1;
if (a == 0) a = LEN;
sb.append(SOURCE.charAt(a - 3));
}
return sb.toString();
}
public static boolean isAlp(String s) {
String p = "^[A-Za-z]+$";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
return true;
}
return false;
}
}
相關(guān)文章
Spring的Bean生命周期之BeanDefinition詳解
這篇文章主要介紹了Spring的Bean生命周期之BeanDefinition詳解,在spring bean創(chuàng)建過程 依賴 BeanDefinition 中的信息處理bean的生產(chǎn),BeanDefinition 是 Spring Framework 中定義 Bean 的配置元信息接口,需要的朋友可以參考下2023-12-12java反射校驗參數(shù)是否是基礎(chǔ)類型步驟示例
這篇文章主要為大家介紹了java反射校驗參數(shù)是否是基礎(chǔ)類型步驟示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12springboot多數(shù)據(jù)源配置及切換的示例代碼詳解
這篇文章主要介紹了springboot多數(shù)據(jù)源配置及切換,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09關(guān)于SpringSecurity簡介以及和Shiro的區(qū)別
這篇文章主要介紹了關(guān)于SpringSecurity簡介以及和Shiro的區(qū)別,在Java應(yīng)用安全領(lǐng)域,Spring Security會成為被首先推崇的解決方案,就像我們看到服務(wù)器就會聯(lián)想到Linux一樣順理成章,需要的朋友可以參考下2023-07-07Mybatis-Plus中and()和or()的使用與原理詳解
最近發(fā)現(xiàn)MyBatisPlus還是挺好用的,下面這篇文章主要給大家介紹了關(guān)于Mybatis-Plus中and()和or()的使用與原理的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09