某系统的数字密码为4位数字,例如:1314。为了其安全性,现在编写一个程序为其加密。
加密规则为:每位数字加2再取余10,最后按顺序反转。
package com.ty.java;
public class encryption {
public static void main(String[] args) {
System.out.println("最终加密为:" + encrypt(1314));
}
public static String encrypt(int number){
int[] n = split(number); //调用split方法给动态数组n
for (int i = 0; i < n.length; i++) {
n[i] = (n[i] + 2) % 10;
}
reverse(n); //调用reverse方法
String finaldata = "";
for (int i = 0; i < n.length; i++) {
finaldata += n[i];
}
return finaldata;
}
private static void reverse(int[] n) {
int t;
for (int i = 0,j =n.length - 1; i < j; i++,j--) {
t = n[j]; //进行数字反转
n[j] = n[i];
n[i] = t;
}
}
public static int[] split(int number){
int[] n = new int[4]; //进行数字拆分
n[0] = number /1000;
n[1] = number / 100 % 10;
n[2] = number / 10 % 10;
n[3] = number % 10;
return n;
}
}
代码运行如下:
com.ty.java.encryption
最终加密为:5013
Process finished with exit code 0