RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。1987年7月首次在美国公布,当时他们三人都在麻省理工学院工作实习。RSA就是他们三人姓氏开头字母拼在一起组成的。
RSA是目前最有影响力和最常用的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。
今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的。但在分布式计算和量子计算机理论日趋成熟的今天,RSA加密安全性受到了挑战和质疑。
RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。
PHP
<?php
/**
* RSA加密PHP版本
*/
class RSA
{
/**
* 对字符串进行RSA加密
*
* @param string $channelPass 待加密字符串
* @return bool|string 加密后十六进制字符串
*/
public static function getSign($channelPass = '')
{
// 不同平台之间转化过的对等公钥文件
$pubKeyFile = "file://" . dirname(__FILE__) . "/publickey.pem";
// 读取公钥内容
$pubKey = file_get_contents($pubKeyFile);
/**
* 从证书中提取公钥并准备使用
* @link http://php.net/manual/zh/function.openssl-pkey-get-public.php
*/
$res = openssl_pkey_get_public($pubKey);
if ($res) {
/**
* 用公钥加密数据
* @link http://php.net/manual/zh/function.openssl-public-encrypt.php
*/
$opt = openssl_public_encrypt($channelPass, $result, $res);
if ($opt) {
/**
* 函数把包含数据的二进制字符串转换为十六进制值
* @link http://php.net/manual/zh/function.bin2hex.php
*/
return bin2hex($result);
}
}
return false;
}
}
echo RSA::getSign('Test password');
echo "\n\n";
Java
package b2c;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
/**
* RSA加密
*/
public class Test {
/**
* 十六进制字符
*/
private static char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static void main(String args[]) {
// 需要加密的字符串
String password = "Test password";
String encodePassword = encryptPassword(password);
System.out.println(encodePassword);
}
/**
* 针对明文密码进行RSA加密
*
* @param clearPassword 待加密字符串
* @return 加密后的字符串
*/
private static String encryptPassword(String clearPassword) {
try {
// 读取RSA的加密公钥
RSAPublicKey publicKey = (RSAPublicKey) readFromFile("public.dat");
// 跟公钥一并进行加密
byte[] encryptBytes = encrypt(clearPassword, publicKey);
if (encryptBytes == null) {
System.out.println("Error");
System.exit(0);
}
// 加密后的字节数组转为十六进制字符串
return toHexString(encryptBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从读取文件Object对象
*
* @param fileName 文件名
* @return 文件对象
*/
private static Object readFromFile(String fileName) {
ObjectInputStream objectInputStream = null;
Object object = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(fileName));
object = objectInputStream.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return object;
}
/**
* 加密,key可以是公钥,也可以是私钥 RSA加密明文最长117位,需要分段加密
*
* @param message 代价密字符串
* @return 加密后的字节数组
*/
private static byte[] encrypt(String message, Key key) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] me = message.getBytes();
byte[] doFinal = null;
byte[] doFinal2;
for (int i = 0; i < me.length; i += 117) {
if (i + 117 > me.length) {
doFinal2 = cipher.doFinal(me, i, me.length - i);
} else {
doFinal2 = cipher.doFinal(me, i, 117);
}
if (doFinal == null) {
doFinal = doFinal2;
} else {
doFinal = join(doFinal, doFinal2);
}
}
return doFinal;
} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
/**
* 连接两个byte数组,之后返回一个新的连接好的byte数组
*
* @param a1 byte[]
* @param a2 byte[]
* @return byte[]
*/
private static byte[] join(byte[] a1, byte[] a2) {
byte[] result = new byte[a1.length + a2.length];
System.arraycopy(a1, 0, result, 0, a1.length);
System.arraycopy(a2, 0, result, a1.length, a2.length);
return result;
}
/**
* byte[]转化为十六进制字符串
*
* @param b byte[]
* @return string
*/
private static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i : b) {
sb.append(HEX[(i & 0xf0) >>> 4]);
sb.append(HEX[i & 0x0f]);
}
return sb.toString();
}
}