如今互联网如火如荼的进行的同时,你是否觉得网络不安全呢?
最近研究了 非对称加密解密的算法,服务端私钥加密,客户端 公约解密
贴上代码 希望对大伙有用
public class RSAEncrypt {
private static String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANCQmb9rsKZcA3js\r"
+ "NnOkcsVpRB9ESjcmMoH7UEv4YYW/AVIJt5W2Suumk6Rp2IEP0VRAEbA10bX/3c5W\r"
+ "ID442RCU2PyJwXBUtx2Rs8NFC2SqEVzmO7I8K/NCEtI7/4WbhrDn4n/KRrhnS4LI\r"
+ "rpnyvyWcOp7VRsu5tGW36DSDgSLRAgMBAAECgYBDxom/883u8b3LIO+8+ra1QjT5\r"
+ "+CYp78bACJwaY/fFD8HtF+1JwHhuRa564k6R+kLrHvrgiUzB2QkKUWCe97hJnU6o\r"
+ "yxgkeuhq021DzfIz2RAEBRsBbsQjPlU81TSA9QUiGwW2Qk+ZKuY77tkqYW+IJplL\r"
+ "ymPmihXyiUfCQDsOdQJBAP3BupieRSQRwRrYkuZ2xzlPxm6n2Mc+aNqQDlukVnIp\r"
+ "Bb7utBeGtryfyGpGAjvWb2/sMzKq3Sbhd9IXL7Wuw4sCQQDSaJlSXBc8RV5wAOHi\r"
+ "oBXDH0Mm2QVSe32DQqJJLsRB2br6H203kOFo5ugkSdRZvUlfy/IQXBeQQfqc1i5i\r"
+ "B86TAkEA8KVzVt7phO5Nai8vCN5lyqUr8q68tx8pgvSQmTn9PSBIMazgH1uDGtiQ\r"
+ "0K/52FNgtQyT9R3ywreZ0SRp+2t0RwJBAK6ypkqZp7klJ4n7UZGmtSry9AB3RFH9\r"
+ "snKfirsUl2LNcs9l9HqkUmOVBL3MhwGThi6B2RP4QqBGB9zcgFpofP0CQQDfHVX9\r"
+ "/aEEbYXENMv26lgUqmVzNq4HTQrYcbb5RsrhEfFpC7NqPilS4WDiIj5iKmmDv+lz\r"
+ "6ASliX8grlgywjJ2\r";
private static Cipher cipher = null;
private static Key privateKey = null;
static {
try {
privateKey = getPrivateKey(PRIVATE_KEY);
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
} catch (Exception e) {
// ignore
}
}
public static String decode(String str) {
if (cipher == null)
return null;
try {
byte[] enBytes = Base64.decode(str.getBytes(), 0);
byte[] deBytes = cipher.doFinal(enBytes);
return new String(deBytes);
} catch (Exception e) {
return null;
}
}
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] enBytes = Base64.decode(key.getBytes(), 0);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(enBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static PublicKey getRSAPublicKey(String publicKeyStr)
throws Exception {
try {
byte[] enBytes = Base64.encode(publicKeyStr.getBytes(),
Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory
.getInstance("RSA/ECB/PKCS1Padding");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(enBytes);
return keyFactory.generatePublic(keySpec);
} catch (Exception e) {
throw null;
}
}
}