js RSA加密 java解密方式

1 篇文章 0 订阅
**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;

import javax.crypto.Cipher;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.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 {
    RSAUtil.generateKeyPair( null, null, 2048 );
}

@Test
public void test( ) throws Exception {
    privateKey = ( RSAPrivateCrtKey ) RSAUtil.parsePrivateKey( PrivateKeyStr );
    publicKey = RSAUtil.parsePublicKey( PublicKeyStr );
    byte[] b = RSAUtil.encrypt( PWD_STRING.getBytes( CharSet ) );
    String pwd = new String( b, CharSet );
    System.out.println( pwd );
    String after = new String( RSAUtil.decrypt( b ) );
    System.out.println( after );
}

@Test
public void test2( ) throws Exception {
    String mi1 = "QNdtyMbWTuCNO6BFfcS716kXHPHJciRBhOmPg+bZepLaJEn8eexUD3o0/Uk+6s4oELKhnrExm3uc6IWMsMmm++qcxnPf0o/pK2w8f6bgNc4eTWqGM3y5N/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 = KeyPairGenerator.getInstance( Algorithm, provider );
    SecureRandom random = new SecureRandom( );
    random.setSeed( System.currentTimeMillis( ) );
    kpg.initialize( size, random );
    KeyPair kp = kpg.generateKeyPair( );
    privateKey = ( RSAPrivateCrtKey ) kp.getPrivate( );
    publicKey = kp.getPublic( );
    System.out.println( "RSA Private CRT Key" );
    RSAPublicKey jce = ( RSAPublicKey ) publicKey;
    String msg = write( new String( Hex.encodeHex( privateKey.getEncoded( ) ) ), "PRIVATE", "_HEX" );
    msg = write( new String( Base64.encode( privateKey.getEncoded( ) ) ), "PRIVATE", "_BASE64" );
    msg = write( new String( Hex.encodeHex( jce.getModulus( ).toByteArray( ) ) ), "PUBLIC", "_HEX" );
    msg = write2( privateKey );
    return msg;

}

public static void main( String[] args ) throws Exception {
    RSAUtil.generateKeyPair( null, null, 2048 );
}

public static String decodeJsValue( String jsValue ) throws Exception {
    byte[] input = Hex.decodeHex( jsValue.toCharArray( ) );
    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 = Cipher.getInstance( 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 );
}

public static byte[] decrypt( byte[] decrypted ) throws Exception {
    return decrypt( decrypted, null );
}

public static byte[] decrypt( byte[] decrypted, String privateString ) throws Exception {
    *Cipher cipher = Cipher.getInstance( "RSA/None/PKCS1Padding", provider );*
    cipher.init( Cipher.DECRYPT_MODE, privateString != null ? parsePrivateKey( privateString ) : privateKey );
    return cipher.doFinal( decrypted );
}

public static RSAPrivateKey parsePrivateKey( String privateKey ) throws Exception {
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec( Base64.decode( privateKey ) );
    KeyFactory keyFactory = KeyFactory.getInstance( Algorithm, provider );
    Key privateK = keyFactory.generatePrivate( pkcs8KeySpec );
    return ( RSAPrivateKey ) privateK;
}

public static RSAPublicKey parsePublicKey( String key ) throws Exception {
    X509EncodedKeySpec x509 = new X509EncodedKeySpec( Base64.decode( key ) );
    KeyFactory kf = KeyFactory.getInstance( 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 ( !path.exists( ) ) {
        path.mkdir( );
    }
    File file = new File( PATH + MERCHANT + "_" + jce + type + KEY_FILE_SUFFIX );
    if ( file.exists( ) ) {
        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 ( !path.exists( ) ) {
        path.mkdir( );
    }
    File file = new File( PATH + MERCHANT + TEXT_FILE_SUFFIX );
    if ( file.exists( ) ) {
        return "file is exists";
    }
    StringBuffer sb = new StringBuffer( );
    sb.append( "Modulus: " ).append( privateKey.getModulus( ) ).append( rn ).append( "PublicExponent: " ).append( privateKey.getPublicExponent( ) )
            .append( rn ).append( "PrivateExponent: " ).append( privateKey.getPrivateExponent( ) ).append( rn ).append( "primeP: " )
            .append( privateKey.getPrimeP( ) ).append( rn ).append( "primeQ: " ).append( privateKey.getPrimeQ( ) ).append( rn ).append( "primeExponentP: " )
            .append( privateKey.getPrimeExponentP( ) ).append( rn ).append( "primeExponentQ: " ).append( privateKey.getPrimeExponentQ( ) ).append( rn )
            .append( "crtCoefficient: " ).append( privateKey.getCrtCoefficient( ) ).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));
}

js下载地址
js加密详解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值