/**
* 字节数据转十六进制字符串
* @param data 输入数据
* @return 十六进制内容
*/
public static String byteArrayToString(byte[] data){
StringBuilder stringBuilder= new StringBuilder();
for (int i=0; i<data.length; i++){
//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]);
//取出字节的低四位 作为索引得到相应的十六进制标识符
stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
if (i<data.length-1){
stringBuilder.append(' ');
}
}
return stringBuilder.toString();
}
public static void main(String[] args){
RSAEncrypt rsaEncrypt= new RSAEncrypt();
//加载公钥
try {
rsaEncrypt.loadPublicKey(new FileInputStream("rsa_public_key.pem"));
System.out.println("加载公钥成功");
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("加载公钥失败");
}
//加载私钥
try {
rsaEncrypt.loadPrivateKey(new FileInputStream("rsa_private_key.pem"));
System.out.println("加载私钥成功");
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("加载私钥失败");
}
//测试字符串
String encryptStr= "taoshihan";
System.out.println("加密前:");
System.out.println(encryptStr);
try {
//加密
byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), encryptStr.getBytes());
//解密
byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), cipher);
BASE64Encoder encode = new BASE64Encoder();
String buffer= encode.encode(cipher);
System.out.println("加密后:");
System.out.println(new String(buffer));
System.out.println("解密后:");
System.out.println(new String(plainText));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
带包编译和执行
javac -cp bcprov-ext-jdk15on-156.jar RSAEncrypt.java
java -cp .:bcprov-ext-jdk15on-156.jar RSAEncrypt
执行结果:
加载公钥成功
加载私钥成功
加密前:
taoshihan
加密后:
Tt1p5XnamZkkVjGn1cVgEIb7U+CP27Xw93JQQUZyc2Up/rJL4Mx+dA8mxkva1a/I64sUTb7QD//8
gbss4bZY/DHrLityTt2/QjjQUFYD5/Aa1m1QKUBulWY4/C5so5dm6wrRnjolsIFUbY+RfH4B6hp1
taQGBRDum/xEX6OsJ9I=
解密后:
taoshihan
shell使用公钥加密,php使用私钥解密
shell:
openssl rsautl -encrypt -in readme.txt -inkey rsa_public_key.pem -pubin|base64
加密后的字符串
lNJ50ODiofcp+adrtAI943HOsjdDTg3UMfUkt0NI7DhUjxCM+NAlBH08WVQRtYK9W8ZoQOta3QH6
PzmJT4WsI0yfNGiUWYgoYgSOtPURSQMbaCt3DM2Y5mEKqzbKLrhN+S+9Jrtmef1VuBUes8wN6rOD
UHxI+vDwQ+utRJRRo9U=
php: