RSA和MD5加密

来源:互联网 发布:平板电脑淘宝怎么开店 编辑:IT博客网 时间:2019/08/18 21:01

加密技术一般分为三类:对称加密、非对称加密和单向Hash技术。

非对称加密的代表是RSA,下面以一个实例说明RSA的加解密过程。

public static void main(String[] args) throws Exception {
String plainTest = "This is a secrecy";
byte[] utf8Array = plainTest.getBytes("UTF-8");

//首先生成一个RSA密钥对:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
//然后初始化RSA Cipher对象并加密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
System.out.println("\n"+cipher.getProvider().getInfo());
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal(utf8Array);
System.out.println("-->"+new String(cipherText,"UTF-8"));

//通过如下代码解密cipherText密文
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println("--->"+new String(newPlainText,"UTF-8"));
}

}


单向hash函数的典型代表 是MD5.

public class MD5 {


public static String create(String s) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");


byte[] byteArray = s.getBytes("ISO-8859-1");
byte[] md5Bytes = md5.digest(byteArray);


StringBuffer hexValue = new StringBuffer();


for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}


return hexValue.toString();


} catch (Exception e) {
e.printStackTrace();
return null;

}

public static void main(String[] args) {
System.out.println(MD5.create("This is a secrecy."));
}


}


当然,我们自己也可写一个简单的加密算法。

public class MyEncription {


public static String create(String s){
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
array[i] = (char) (array[i]^20000);
}
return new String(array);
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入一个英文字符串或解密字符串");
String password = in.nextLine();
String newPass = MyEncription.create(password);
System.out.println("加密或解密结果如下:");
System.out.println(newPass);
}


}