简体   繁体   English

我如何拥有自己的公钥来加密数据?

[英]How do I have my own public key to encrypt data?

I have a User class, an Entity, and it must write the user's name and email in encrypted form with an asymmetric key (RSA) of size 2048.我有一个用户 class,一个实体,它必须使用大小为 2048 的非对称密钥 (RSA) 以加密形式写入用户名和 email。

The information will be encrypted with the public key of the client and he will decrypt using his private key.信息将使用客户的公钥加密,他将使用他的私钥解密。

@Entity
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String nome;

    private String email;

    @JsonBackReference
    @ManyToMany
    @JoinTable(name = "USUARIO_DIGITO", joinColumns = @JoinColumn(name = "usuario_id"), inverseJoinColumns = @JoinColumn(name = "digito_id"))
    private Set<DigitoUnico> resultadosDigitoUnico;
    
    ....
    getters and setters
    
}

In the user service I call the methods created for encryption and decryption.在用户服务中,我调用了为加密和解密创建的方法。

@Service
public class UsuarioService implements IUsuarioService {

    @Autowired
    private IUsuarioRepository usuarioRepository;   
    
....

    public Usuario adicionar(Usuario usuario) {
        
        usuario.setId(null);
        usuario.setResultadosDigitoUnico(null);
        
        try {
            return usuarioRepository.save(encriptarDadosUsuario(usuario));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
        private Usuario encriptarDadosUsuario(Usuario usuario) throws Exception {
        usuario.setEmail(EncriptaDadosUsuario.encriptar(usuario.getEmail(), EncriptaDadosUsuario.gerarParDeChaves().getPublic()));
        usuario.setNome(EncriptaDadosUsuario.encriptar(usuario.getNome(), EncriptaDadosUsuario.gerarParDeChaves().getPublic()));
        return usuario;
    }
    
    private Usuario decriptarDadosUsuario(Usuario usuario) throws Exception{
        usuario.setEmail(EncriptaDadosUsuario.decriptar(usuario.getEmail(),EncriptaDadosUsuario.gerarParDeChaves().getPrivate()));
        usuario.setNome(EncriptaDadosUsuario.decriptar(usuario.getNome(),EncriptaDadosUsuario.gerarParDeChaves().getPrivate()));
        return usuario;
    }
}

But, I must create an endpoint for sending this user's public key, to client, for encryption.但是,我必须创建一个端点来将此用户的公钥发送到客户端以进行加密。

How can I have my public key, and use it for this encryption and decryption?我怎样才能拥有我的公钥,并将其用于此加密和解密?

Below my class to encrypt:下面我class来加密:

public class EncriptaDadosUsuario {

    public static KeyPair gerarParDeChaves() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("SHA256withRSA");
        generator.initialize(2048, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();

        return pair;
    }
    
    
    public static String encriptar(String plainText, PublicKey publicKey) throws Exception {
        Cipher encryptCipher = Cipher.getInstance("SHA256withRSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(cipherText);
    }
    
    public static String decriptar(String cipherText, PrivateKey privateKey) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(cipherText);

        Cipher decriptCipher = Cipher.getInstance("SHA256withRSA");
        decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);

        return new String(decriptCipher.doFinal(bytes), StandardCharsets.UTF_8);
    }
    
}

You try to generate RSA keys that can be used for signature but not for enryption when instantiating the keypairgenerator and cipher with "SHA256withRSA".在使用“ SHA256withRSA ”实例化密钥对生成器和密码时,您尝试生成可用于签名但不能用于加密的 RSA 密钥。

You need to change the KeyPairGenerator to "RSA" and the Cipher to "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING" [or other available ciphers on your Java] to get your piece of code to run.您需要将 KeyPairGenerator 更改为“RSA”,将 Cipher 更改为“RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING”[或 Java 上的其他可用密码],才能让您的代码运行。

Below you find parts of your code with the corrections and a small example that encrypts an email address and later decrypts the ciphertext to the decryptedtext.您可以在下面找到包含更正的部分代码和一个加密 email 地址并稍后将密文解密为解密文本的小示例。

Please note that this example code does have no exception handling and is for educational purpose only.请注意,此示例代码没有异常处理,仅用于教育目的。

output: output:

How do I have my own public key to encrypt data
ciphertext: lVN6XLO7LxMASVifq2J1/T8Hv40AUeOml3+MjA6u+mKv1EcJHQO7gbZpMCrhO1fzo3s5tGRQl38iumMDqLBp+ApxQkPKeVVU99oOeuzYZb9fwyBH1/b4AEC1UDdFBWwH6rN/MuG17FyBrq/JR64upcM79gITdrIywvd32gYCd+XrGcGIxDoDGufQ1iqjjOihnRdYkYQDhUNEhi3clTz+ZDJ1EqMZmfc+v9Fsnsit2q9wbO3C33Hjbj/gY8AIMOpE7KYGupnpvR+WQk1DvmqiDoIDNfweRvwqF9m+7AUldAxxmjPN0C/WFmYPfZHUFSBK/0+8Ix5pDNw4l3C8thWKeg==
decryptedtext: myEmail@stackoverflow.com

code:代码:

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("How do I have my own public key to encrypt data");
        // string to encrypt
        String plaintext = "myEmail@stackoverflow.com";
        // keypair generation
        KeyPair keyPair = gerarParDeChaves();
        // encryption
        PublicKey publicKey = keyPair.getPublic();
        String ciphertext = encriptar(plaintext, publicKey);
        System.out.println("ciphertext: " + ciphertext);
        // decryption
        PrivateKey privateKey = keyPair.getPrivate();
        String decryptedtext = decriptar(ciphertext, privateKey);
        System.out.println("decryptedtext: " + decryptedtext);
    }
    public static KeyPair gerarParDeChaves() throws Exception {
        //KeyPairGenerator generator = KeyPairGenerator.getInstance("SHA256withRSA"); // used for signatures
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();
        return pair;
    }

    public static String encriptar(String plainText, PublicKey publicKey) throws Exception {
        //Cipher encryptCipher = Cipher.getInstance("SHA256withRSA"); // used for signatures
        Cipher encryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(cipherText);
    }

    public static String decriptar(String cipherText, PrivateKey privateKey) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(cipherText);
        //Cipher decriptCipher = Cipher.getInstance("SHA256withRSA"); // used for signatures
        Cipher decriptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(decriptCipher.doFinal(bytes), StandardCharsets.UTF_8);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java的RSA私钥和公钥加密并发送DES密钥? - How do I encrypt and send DES key with RSA private key and then public key in Java? 如何使用RSA公钥加密java.util.Properties对象(可以是任意大小)? - How do I encrypt a java.util.Properties object (can be any size) using an RSA Public Key? 加密解密我自己的密钥而不是生成java - Encrypt Decrypt my own key not generated java 我应该使用哪些加密算法来使用私钥加密数据并使用公钥解密数据? - What cryptographic algorithms should I use to encrypt data using private key and decrypt data using public key? 如何使用公共/私人密钥对加密SSO令牌? - How do I use a Public/Private KeyPair to encrypt an SSO token? 如何使用java生成的public加密nodejs中的字符串 - How do I encrypt string in nodejs with public generated by java 即使发送方使用修改后的公钥加密数据,接收方也可以使用私钥解密数据。 这怎么可能? - Receiver is able to decrypt the data with private key even if sender encrypt the data with modified public key. How is it possible? 我已经通过 Java spring 安全性生成了公钥,我尝试使用该公钥来使用 Nodejs Crypto 加密数据,但它返回错误 - I had generate Public Key by Java spring security and I try to use that public key to encrypt data with Nodejs Crypto but it return error 给定哈希表中的键,如果我的值有多种数据类型,我如何返回值 - Given Key in HashTable how do I return the value if my value have multiple data types Bouncycastle:使用公钥加密 - Bouncycastle: encrypt with a public key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM