jsRSA加密java解密⽅式
**js 使⽤rsa公钥加密⼀般有两种,在这是使⽤java⽣成的密钥对
JAVA⽣成密钥对,以及加解密的代码**
package com.sg.demo.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
pto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.ders.Base64;
import org.junit.Test;
public class RSAUtil {
private static PublicKey publicKey;
private static RSAPrivateCrtKey privateKey;
private static final String Algorithm = “RSA”;//使⽤base64编码解密时⽤:”RSA/None/PKCS1Padding” private static final String CharSet = “UTF-8”;
private static String PublicKeyStr = “”;
private static String PrivateKeyStr = “”;
private static final String PWD_STRING = “000000”;
private static String MERCHANT = “TEST”;
private static final String KEY_FILE_SUFFIX = “.key”;
private static final String TEXT_FILE_SUFFIX = “.txt”;
private static String PATH = “F:\” + MERCHANT + “\”;
/**
* @throws Exception
*            ⽣成key
*/
@Test
public void generateKeyPairTest( ) throws Exception {
}
@Test
public void test( ) throws Exception {
privateKey = ( RSAPrivateCrtKey ) RSAUtil.parsePrivateKey( PrivateKeyStr );
publicKey = RSAUtil.parsePublicKey( PublicKeyStr );
byte[] b = pt( Bytes( CharSet ) );
String pwd = new String( b, CharSet );
System.out.println( pwd );
String after = new String( RSAUtil.decrypt( b ) );
String after = new String( RSAUtil.decrypt( b ) );
System.out.println( after );
}
@Test
public void test2( ) throws Exception {
String mi1 = "QNdtyMbWTuCNO6BFfcS716kXHPHJciRBhOmPg+bZepLaJEn8eexUD3o0/Uk+6s4oELKhnrExm3uc6IWMsMmm++qcxnPf0o/pK2w8f6bgN c4eTWqGM3y5N/TGxof1/kG36fefWEyukK6CMXUQZM/hNMwNmTwS4c8qQ5stiwJL0YM=";
String after1 = new String( RSAUtil.decrypt( Base64.decode( mi1 ), PrivateKeyStr ), CharSet );
System.out.println( after1 );
}
public static String generateKeyPair( String m, String url, int size ) throws Exception {
if ( m != null ) {
MERCHANT = m;
}
if ( url != null ) {
PATH = url;
}
KeyPairGenerator kpg = Instance( Algorithm, provider );
SecureRandom random = new SecureRandom( );
random.setSeed( System.currentTimeMillis( ) );
kpg.initialize( size, random );
KeyPair kp = ateKeyPair( );
privateKey = ( RSAPrivateCrtKey ) kp.getPrivate( );
publicKey = kp.getPublic( );
System.out.println( "RSA Private CRT Key" );
RSAPublicKey jce = ( RSAPublicKey ) publicKey;
String msg = write( new String( deHex( Encoded( ) ) ), "PRIVATE", "_HEX" );
msg = write( new String( de( Encoded( ) ) ), "PRIVATE", "_BASE64" );
msg = write( new String( deHex( Modulus( ).toByteArray( ) ) ), "PUBLIC", "_HEX" );
msg = write2( privateKey );
return msg;
}
public static void main( String[] args ) throws Exception {
}
public static String decodeJsValue( String jsValue ) throws Exception {
byte[] input = Hex.decodeHex( CharArray( ) );
byte[] raw = decrypt( input, PrivateKeyStr );
// 标志位为0之后的是输⼊的有效字节
int i = raw.length - 1;
while ( i > 0 && raw[ i ] != 0 ) {
i--;
}
i++;
byte[] data = new byte[ raw.length - i ];
for ( int j = i; j < raw.length; j++ ) {
data[ j - i ] = raw[ j ];
}
return new String( data, CharSet );
}
public static byte[] encrypt( byte[] encrypted, String publicString ) throws Exception {
Cipher cipher = Instance( Algorithm, provider );
cipher.init( Cipher.ENCRYPT_MODE, publicString != null ? parsePublicKey( publicString ) : publicKey );
return cipher.doFinal( encrypted );
}
public static byte[] encrypt( byte[] encrypted ) throws Exception {
return encrypt( encrypted, null );
return encrypt( encrypted, null );
}
public static byte[] decrypt( byte[] decrypted ) throws Exception {
return decrypt( decrypted, null );
}
public static byte[] decrypt( byte[] decrypted, String privateString ) throws Exception {
*Cipher cipher = Instance( "RSA/None/PKCS1Padding", provider );*
cipher.init( Cipher.DECRYPT_MODE, privateString != null ? parsePrivateKey( privateString ) : privateKey );    return cipher.doFinal( decrypted );
}js代码加密软件
public static RSAPrivateKey parsePrivateKey( String privateKey ) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec( Base64.decode( privateKey ) );    KeyFactory keyFactory = Instance( Algorithm, provider );
Key privateK = atePrivate( pkcs8KeySpec );
return ( RSAPrivateKey ) privateK;
}
public static RSAPublicKey parsePublicKey( String key ) throws Exception {
X509EncodedKeySpec x509 = new X509EncodedKeySpec( Base64.decode( key ) );
KeyFactory kf = Instance( Algorithm, provider );
return ( RSAPublicKey ) kf.generatePublic( x509 );
}
private static Provider provider = new BouncyCastleProvider( );
static String rn = "\n";
private static String write( String key, String jce, String type ) throws IOException {
File path = new File( PATH );
if ( !ists( ) ) {
path.mkdir( );
}
File file = new File( PATH + MERCHANT + "_" + jce + type + KEY_FILE_SUFFIX );
if ( ists( ) ) {
return "file is exists";
}
StringBuffer sb = new StringBuffer( );
sb.append( "-----BEGIN RSA " ).append( jce ).append( " KEY-----" ).append( rn );
OutputStream outputStream = new FileOutputStream( file );
System.out.println( key );
int a = 0;
for ( int n = 0; n < key.length( ); n++ ) {
if ( a % 64 == 0 && n != 0 ) {
sb.append( rn );
}
sb.append( key.substring( a, ++a ) );
}
sb.append( rn );
sb.append( "-----END RSA " ).append( jce ).append( " KEY-----" ).append( rn );
outputStream.write( sb.toString( ).getBytes( ) );
outputStream.close( );
return "SUCCESS";
}
private static String write2( RSAPrivateCrtKey privateKey ) throws IOException {
File path = new File( PATH );
if ( !ists( ) ) {
path.mkdir( );
}
File file = new File( PATH + MERCHANT + TEXT_FILE_SUFFIX );
if ( ists( ) ) {
return "file is exists";
}
}
StringBuffer sb = new StringBuffer( );
sb.append( "Modulus: " ).append( Modulus( ) ).append( rn ).append( "PublicExponent: " ).append( PublicExponent( ) )
.append( rn ).append( "PrivateExponent: " ).append( PrivateExponent( ) ).append( rn ).append( "primeP: " )
.append( PrimeP( ) ).append( rn ).append( "primeQ: " ).append( PrimeQ( ) ).append( rn ).append( "primeExponentP: " )
.append( PrimeExponentP( ) ).append( rn ).append( "primeExponentQ: " ).append( PrimeExponentQ( ) ).append( rn )            .append( "crtCoefficient: " ).append( CrtCoefficient( ) ).append( rn );
OutputStream outputStream = new FileOutputStream( file );
outputStream.write( sb.toString( ).getBytes( ) );
outputStream.close( );
return "SUCCESS";
}
}
//1.hex转码⽅式
function hex(){
setMaxDigits(262); //设置模指数
var key = ‘00d4b863240500f5174’;//公钥字符串
var publicKey = new RSAKeyPair(‘10001’, ”, key); //创建公钥
var password = ‘123456’;
var pwd = encryptedString(publicKey, password) ;
}
// 2.base64转码⽅式
function linebrk(s,n) {
var ret = “”;
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + “\n”;
i += n;
}
return ret + s.substring(i,s.length);
}
function base64(){
setMaxDigits(262); //设置模指数
var key = ‘00d4b863240500f5174’;//公钥字符串
var publicKey = new RSAKeyPair(‘10001’, ”, key); //创建公钥
var password = ‘123456’;
var pwd = encryptedString(publicKey, password) ;
var base64Pwd = linebrk(hex2b64(encryPssword,64));
}