PHP代码:
<?php
$privateKeyFilePath = '-----BEGIN RSA PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJDArkki2k3+xhze
v5emztqFtUhOzVlSveQ5dOLC4nNlLg8r81I9xBaXB7m4rb6lVjLgUuAXKUJ8y7yH
eE02s695cR/ZD0fierrMKMkmTFZIqOVYchn15N8EPz5e8WFirtP+Kaol4jDOaLCP
CSIs8QrQE6kEC7WDBi2/0mCkNI7PAgMBAAECgYB0oZuMODXXZDGyb1PGWFQRRGyl
n0Db+MwiCJ2CXG5jdiHffZUnLbdCUFycKw5rLwK+KXr9LgxDkxQBitHGvQ2XXO8w
v/2MQT658Eb49iQxZfuuhFFN8YIJZ4oFVyQQWXyCRAopyi/B0Eh6LTTTPjC/udPX
MoC0vSZl93Db8KPdyQJBANLPOnmyQmua6za/fFhWl13lsa+Ko73LhGi6dpiBjdpw
j0hp6NV/7yGCvHJFUr0hc9p5/lVJHkeAS/QtxF1IqXMCQQCvyGVL5uXj4didkO50
4HDgpPAgdROCZ6KrrNIf+RnCDn9Ffa1oA+n5cnno4trZVAYLU4yzZ63tQ/Z81ZfS
+h41AkBPXuyyUzaE0zBKTbBghkG5fbj30egyloTE9aefZe/l1clsx0t9zwxW/qU7
FPTA9u5qzNHAhKYc36Y5Sl4LjUcXAkBX50mopEXQKI+Pc/ubHOW1oSWnxYRFERhK
63iEnqgf3+oLUSbXPiXSJUoLiO5SAe+n2FcjHDTg0ry/fnyW95cFAkEAyllpaHTu
V5FPt6J5wZcEUbZoZsxYGmfUEg6HUE8BbGgRWwaem94p668ILaqGtxGKLKgbWoTM
Z8ZM+5cR/+C+yA==
-----END RSA PRIVATE KEY-----';
/**
* 公钥文件的路径
*/
$publicKeyFilePath = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQwK5JItpN/sYc3r+Xps7ahbVI
Ts1ZUr3kOXTiwuJzZS4PK/NSPcQWlwe5uK2+pVYy4FLgFylCfMu8h3hNNrOveXEf
2Q9H4nq6zCjJJkxWSKjlWHIZ9eTfBD8+XvFhYq7T/imqJeIwzmiwjwkiLPEK0BOp
BAu1gwYtv9JgpDSOzwIDAQAB
-----END PUBLIC KEY-----';
extension_loaded('openssl') or die('php需要openssl扩展支持');
/**
* 生成Resource类型的密钥,如果密钥文件内容被破坏,openssl_pkey_get_private函数返回false
*/
$privateKey =openssl_pkey_get_private($privateKeyFilePath);
/**
* 生成Resource类型的公钥,如果公钥文件内容被破坏,openssl_pkey_get_public函数返回false
*/
$publicKey =openssl_pkey_get_public($publicKeyFilePath);
($privateKey) or die('密钥不可用');
($publicKey) or die('公钥不可用');
/**
* 原数据
*/
$originalData = 'test';
/**
* 加密以后的数据,用于在网路上传输
*/
$encryptData = '';
echo '原数据为:', $originalData, '<br />';
///用公钥加密
if (openssl_public_encrypt($originalData,$encryptData, $publicKey)) {
//Uu3FzghBLs3dnWEO8Gc7p1QGf2MH+VMddUk0ui2TQlcKbr+DMKRJfsTiQYh5N9Bu+kEyKG72f90l34rNJAkLruZJtuqRTfZ8vnG2P1UEkW+7063GVPz6o6mfrL46FN4j0mpIP6sAshvvUAGudlVTde2KT7bI8E0EqZU9D7WRKCI=
echo '加密成功,加密后数据(base64_encode后)为:', base64_encode($encryptData), '<br />';
echo '加密成功,加密后数据(bin2hex后)为:',bin2hex($encryptData), '<br/>';
} else {
die('加密失败');
}
// $secret = 'iZEksazCdYhkbqM2kRMo9E+oSFCYnTkB0JGOMN5m3ZeJr8ShtrifvHMWQG605pMvO31oalcU8P8jzkEMLyCV0/ATc2AEF6cxwRujl315tB5RClq8aMYhcAlfOTZeuQHJPg3tM98snEVTrVsRJzr94VYcA394yyln+j+44+3wNaWMNSr+7H/H33XmFN9TcE70Jt1AC/PYNLr0an2DNwBtiDt4ttPfHF2iYJqtrH/K/UNxHd5uakpMKX7QRqEYq3Z6d6dCtlv76Ex2SVTWdNofqu7GbMMemo5hEfRf80q8O0o0Kqn3o6cQ13X7aWY/1pGhkfeoC0yauZx4wKrpdmjgd4lCHDlCVgwLiUdG/6U+ckd4CGu7cQtjfy7UKwOJkCqrB+AGbdjaIyiBGdkji39zf2eGJHRzXCVvN3nyRd/AQlwX0sDsICS+R26SNkDmKo8aWBQspzLUkPMZWGyFRy8cRnILYJwpr4Qhq7JKajHQkaAG6RLQ91NsSEhOGMunAQFver4hsk22NRAY5NugT8qOsUarALucT5fwlpDoOEF4lGpF4uLmTGSPMBrptRrPgWSdGs0p/G/pSx9INOgd5X5e/F12GLqIfZIA6JVyQL4E5AQ0S+aZPNdyEiL1Ufz5A5LcILue/PES5ot45LjynTLWZ2lMRiohBeAsEU57j4KCn8QTTiDdRss+qM7UaCrILUrE6C5/PMPOVHxvICsDYmTLY7nfY2M5cH/wPpuPzcbhWlLltk3wmgf34BugVa2mjq8l5x9EoWv+YDXBWqsegL3DpfhMfvAC2Lk1dsiXPpNLgaX+oY6Xy+0T9paCIWs1ZV8A7M2eNWZPMOOiXOZx+l4TTHNrsQCrUTQzCOu+prmerv6QMEKri+X0hfNmBMl9qodlLo3BI1JtDql/g/2qq1Aq8ETkZ9UznLETxwvvqosZjiobhHnKvlH9kaEjsK5XwGX9q4+yJVNAY5IB5DL3uFdnmnUr7GT1o/+8scJQ0WunBWroUYqpb1hr2p+RvzS8PgpA';
// $encryptData = base64_decode($secret);
// var_dump(strlen($encryptData));
///用私钥解密
$decryptData ='';
$crypto = '';
foreach (str_split($encryptData, 128) as $chunk) {
openssl_private_decrypt($chunk,$decryptData, $privateKey);
$crypto .= $decryptData;
}
echo '解密成功,解密后数据为:',$crypto, '<br />';
// if (openssl_private_decrypt($encryptData,$decryptData, $privateKey)) {
// echo '解密成功,解密后数据为:',$decryptData, '<br />';
// } else {
// die('解密成功');
// }
?>
JAVA代码:
public static void main(String[] args) throws Exception {
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQwK5JItpN/sYc3r+Xps7ahbVITs1ZUr3kOXTiwuJzZS4PK/NSPcQWlwe5uK2+pVYy4FLgFylCfMu8h3hNNrOveXEf2Q9H4nq6zCjJJkxWSKjlWHIZ9eTfBD8+XvFhYq7T/imqJeIwzmiwjwkiLPEK0BOpBAu1gwYtv9JgpDSOzwIDAQAB";
String test = encrypt("test", getPublicKey(publicKey));
System.out.println(test);
String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJDArkki2k3+xhzev5emztqFtUhOzVlSveQ5dOLC4nNlLg8r81I9xBaXB7m4rb6lVjLgUuAXKUJ8y7yHeE02s695cR/ZD0fierrMKMkmTFZIqOVYchn15N8EPz5e8WFirtP+Kaol4jDOaLCPCSIs8QrQE6kEC7WDBi2/0mCkNI7PAgMBAAECgYB0oZuMODXXZDGyb1PGWFQRRGyln0Db+MwiCJ2CXG5jdiHffZUnLbdCUFycKw5rLwK+KXr9LgxDkxQBitHGvQ2XXO8wv/2MQT658Eb49iQxZfuuhFFN8YIJZ4oFVyQQWXyCRAopyi/B0Eh6LTTTPjC/udPXMoC0vSZl93Db8KPdyQJBANLPOnmyQmua6za/fFhWl13lsa+Ko73LhGi6dpiBjdpwj0hp6NV/7yGCvHJFUr0hc9p5/lVJHkeAS/QtxF1IqXMCQQCvyGVL5uXj4didkO504HDgpPAgdROCZ6KrrNIf+RnCDn9Ffa1oA+n5cnno4trZVAYLU4yzZ63tQ/Z81ZfS+h41AkBPXuyyUzaE0zBKTbBghkG5fbj30egyloTE9aefZe/l1clsx0t9zwxW/qU7FPTA9u5qzNHAhKYc36Y5Sl4LjUcXAkBX50mopEXQKI+Pc/ubHOW1oSWnxYRFERhK63iEnqgf3+oLUSbXPiXSJUoLiO5SAe+n2FcjHDTg0ry/fnyW95cFAkEAyllpaHTuV5FPt6J5wZcEUbZoZsxYGmfUEg6HUE8BbGgRWwaem94p668ILaqGtxGKLKgbWoTMZ8ZM+5cR/+C+yA==";
String decrypt = decrypt(test, getPrivateKey(privateKey));
System.out.println(decrypt);
}
/**
* RSA解密
*
* @param data
* 待解密数据
* @param privateKey
* 私钥
* @return
*/
public static String decrypt(String data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
}
/**
* RSA加密
*
* @param data
* 待加密数据
* @param publicKey
* 公钥
* @return
*/
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return new String(Base64.encodeBase64String(encryptedData));
}
在linux上生成privateKey,
openssl genrsa -out rsa_private_key.pem 1024
根据privateKey生成publicKey
openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
将java私钥或公钥转换成pem格式,php代码:
<?php
class entry {
var $pub_key;
function redPukey()
{
$pubKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJDArkki2k3+xhzev5emztqFtUhOzVlSveQ5dOLC4nNlLg8r81I9xBaXB7m4rb6lVjLgUuAXKUJ8y7yHeE02s695cR/ZD0fierrMKMkmTFZIqOVYchn15N8EPz5e8WFirtP+Kaol4jDOaLCPCSIs8QrQE6kEC7WDBi2/0mCkNI7PAgMBAAECgYB0oZuMODXXZDGyb1PGWFQRRGyln0Db+MwiCJ2CXG5jdiHffZUnLbdCUFycKw5rLwK+KXr9LgxDkxQBitHGvQ2XXO8wv/2MQT658Eb49iQxZfuuhFFN8YIJZ4oFVyQQWXyCRAopyi/B0Eh6LTTTPjC/udPXMoC0vSZl93Db8KPdyQJBANLPOnmyQmua6za/fFhWl13lsa+Ko73LhGi6dpiBjdpwj0hp6NV/7yGCvHJFUr0hc9p5/lVJHkeAS/QtxF1IqXMCQQCvyGVL5uXj4didkO504HDgpPAgdROCZ6KrrNIf+RnCDn9Ffa1oA+n5cnno4trZVAYLU4yzZ63tQ/Z81ZfS+h41AkBPXuyyUzaE0zBKTbBghkG5fbj30egyloTE9aefZe/l1clsx0t9zwxW/qU7FPTA9u5qzNHAhKYc36Y5Sl4LjUcXAkBX50mopEXQKI+Pc/ubHOW1oSWnxYRFERhK63iEnqgf3+oLUSbXPiXSJUoLiO5SAe+n2FcjHDTg0ry/fnyW95cFAkEAyllpaHTuV5FPt6J5wZcEUbZoZsxYGmfUEg6HUE8BbGgRWwaem94p668ILaqGtxGKLKgbWoTMZ8ZM+5cR/+C+yA==";
$pem = chunk_split($pubKey,64,"\n");//转换为pem格式的公钥
$pem = "-----BEGIN RSA PRIVATE KEY-----\n".$pem."-----END RSA PRIVATE KEY-----\n";
var_dump($pem);
$publicKey = openssl_pkey_get_public($pem);
return $publicKey;
}
}
$entry = new entry();
$entry->redPukey();
?>