java

位置:IT落伍者 >> java >> 浏览文章

java RSA 加解密


发布日期:2022年12月29日
 
java RSA 加解密

import javasecurityKey;

import javasecurityKeyFactory;

import javasecurityKeyPair;

import javasecurityKeyPairGenerator;

import javasecurityPrivateKey;

import javasecurityPublicKey;

import javasecurityinterfacesRSAPrivateKey;

import javasecurityinterfacesRSAPublicKey;

import javasecurityspecPKCSEncodedKeySpec;

import javasecurityspecXEncodedKeySpec;

import javaxcryptoCipher;

import sunmiscBASEDecoder;

import sunmiscBASEEncoder;

public class RSACoder {

/**

* 得到公钥

* @param key 密钥字符串(经过base编码)

* @throws Exception

*/

public static PublicKey getPublicKey(String key) throws Exception {

byte[] keyBytes;

keyBytes = (new BASEDecoder())decodeBuffer(key);

XEncodedKeySpec keySpec = new XEncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactorygetInstance(RSA);

PublicKey publicKey = keyFactorygeneratePublic(keySpec);

return publicKey;

}

/**

* 得到私钥

* @param key 密钥字符串(经过base编码)

* @throws Exception

*/

public static PrivateKey getPrivateKey(String key) throws Exception {

byte[] keyBytes;

keyBytes = (new BASEDecoder())decodeBuffer(key);

PKCSEncodedKeySpec keySpec = new PKCSEncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactorygetInstance(RSA);

PrivateKey privateKey = keyFactorygeneratePrivate(keySpec);

return privateKey;

}

/**

* 得到密钥字符串(经过base编码)

* @return

*/

public static String getKeyString(Key key) throws Exception {

byte[] keyBytes = keygetEncoded();

String s = (new BASEEncoder())encode(keyBytes);

return s;

}

public static void main(String[] args) throws Exception {

KeyPairGenerator keyPairGen = KeyPairGeneratorgetInstance(RSA);

//密钥位数

keyPairGeninitialize();

//密钥对

KeyPair keyPair = keyPairGengenerateKeyPair();

// 公钥

PublicKey publicKey = (RSAPublicKey) keyPairgetPublic();

// 私钥

PrivateKey privateKey = (RSAPrivateKey) keyPairgetPrivate();

String publicKeyString = getKeyString(publicKey);

Systemoutprintln(public:\n + publicKeyString);

String privateKeyString = getKeyString(privateKey);

Systemoutprintln(private:\n + privateKeyString);

//加解密类

Cipher cipher = CiphergetInstance(RSA);//CiphergetInstance(RSA/ECB/PKCSPadding);

//明文

byte[] plainText = 我们都很好!邮件getBytes();

//加密

cipherinit(CipherENCRYPT_MODE publicKey);

byte[] enBytes = cipherdoFinal(plainText);

//通过密钥字符串得到密钥

publicKey = getPublicKey(publicKeyString);

privateKey = getPrivateKey(privateKeyString);

//解密

cipherinit(CipherDECRYPT_MODE privateKey);

byte[]deBytes = cipherdoFinal(enBytes);

publicKeyString = getKeyString(publicKey);

Systemoutprintln(public:\n +publicKeyString);

privateKeyString = getKeyString(privateKey);

Systemoutprintln(private:\n + privateKeyString);

String s = new String(deBytes);

Systemoutprintln(s);

}

}

               

上一篇:Java扫雷算法

下一篇:浅谈Java中用动态代理类实现记忆功能