如何使用RSA算法加密密码?

时间:2016-08-02 02:31:55

标签: java encryption rsa

我是加密新手,我收到了这些说明

  

使用RSA算法,并使用PKCS#1.5 padding(不是OAEP),并将结果添加到加密流中 - 这将成为加密密码。“我的代码中的字符串os是公钥。

我进口了一些罐子; org-apache-commons-codec.jarbcprov-jdk15-130.jar

由于某些原因,我在此行System.out.println("\n"+ "\n" +"encryptionresult" + "\n" + "\n" + Base64.toBase64String(cipher.doFinal(initiatorpassword.getBytes())) + "\n");

上收到错误

错误仅在整个字符串上突出显示toBase64String

  

错误:“无法找到符号方法toBase64String。”

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.bouncycastle.util.encoders.Base64;
import sun.misc.BASE64Decoder;

public class encrypt {

    public static void main(String[] args) {

        encrypt obj = new encrypt();

        obj.process();
    }

    public void process() {


        try {

            String initiatorpassword = "giddibon!";    


            String os = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqLcFdVcV7HdEOotsNLoMPhD74CX1ejzcgfNuiJNy9pTySxbszRBCWxmok3Unul4rX/zyVD/6vDb9nbqRywZIgR46UOn+tR3vGXXPX6igxgS6DYTaQV8W858yOGLuoYwRi5xeQJfczAMU4o+sCxlBbMCqYs4nzW81fi8iF2OEUdrfJcbamhSnksdgfD/nomWy9MESAz1QufrOBnaRX2N0CKsi8SNmzsghpfP15VLiIVV8YXPFKtd9sY37FpY28OKGjKG5wdije/bzFL8qEcPDhqYGuVaGkhX1bkI0iH+UcFtYYrZv/Fyb5jRHXmNLiq4mMG0fMH8ENxNACFtRZTDIIQIDAQAB";


            PublicKey publickeyos = rpos(os);


            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");


            cipher.init(Cipher.ENCRYPT_MODE, publickeyos);

             //error on this line
            System.out.println("\n"+ "\n" +"encryptionresult" + "\n" + "\n" + Base64.toBase64String(cipher.doFinal(initiatorpassword.getBytes())) + "\n");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public PublicKey rpos(String file) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {


        byte[] keyBytes = file.getBytes();

        String pubKey = new String(keyBytes);

        BASE64Decoder decoder = new BASE64Decoder();

        keyBytes = decoder.decodeBuffer(pubKey);

        // generate public key
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFactory.generatePublic(spec);        

        return publicKey;

    }
}

2 个答案:

答案 0 :(得分:1)

您正在寻找的方法是

<强> org.bouncycastle.util.encoders.Base64.encode(byte[] data)

我不确定您在哪里获得对Base64.toBase64String的引用,但快速搜索显示它与类似的C#方法非常接近。

答案 1 :(得分:-1)

我猜你必须使用如下的方法并检查它是否编译

Base64.getEncoder().encodeToString(cipher.doFinal(initiatorpassword.getBytes()))