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

huangapple go评论74阅读模式
英文:

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

问题

// 以下是您提供的内容的翻译:

// 我有一个用户类,一个实体,必须使用大小为2048的非对称密钥(RSA)以加密形式编写用户的名称和电子邮件。

// 信息将使用客户端的公钥进行加密,他将使用私钥进行解密。

@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;

    // ... 获取器和设置器 ...

}

// 在用户服务中,我调用了为加密和解密创建的方法。

@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) {
            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;
    }
}

// 但是,我必须创建一个端点来发送这个用户的公钥,给客户端用于加密。

// 我如何获得我的公钥,并将其用于此加密和解密?

// 以下是我的加密类:

public class EncriptaDadosUsuario {

    public static KeyPair gerarParDeChaves() throws Exception {
        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("RSA");
        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("RSA");
        decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);

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

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.

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 = &quot;USUARIO_DIGITO&quot;, joinColumns = @JoinColumn(name = &quot;usuario_id&quot;), inverseJoinColumns = @JoinColumn(name = &quot;digito_id&quot;))
private Set&lt;DigitoUnico&gt; 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:

public class EncriptaDadosUsuario {
public static KeyPair gerarParDeChaves() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(&quot;SHA256withRSA&quot;);
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(&quot;SHA256withRSA&quot;);
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(&quot;SHA256withRSA&quot;);
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), StandardCharsets.UTF_8);
}
}

答案1

得分: 2

你尝试生成可用于签名但不适用于加密的RSA密钥对,当初始化密钥对生成器和密码器时,使用"SHA256withRSA"。

你需要将KeyPairGenerator更改为"RSA",将Cipher更改为"RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING" [或Java中其他可用的密码器],以使你的代码运行起来。

以下是带有修正的代码部分和一个小示例,该示例加密了电子邮件地址,然后将密文解密为解密文本。

请注意,此示例代码没有异常处理,并仅供教育目的使用。

输出:

如何拥有自己的公钥以加密数据
密文:lVN6XLO7LxMASVifq2J1/T8Hv40AUeOml3+MjA6u+mKv1EcJHQO7gbZpMCrhO1fzo3s5tGRQl38iumMDqLBp+ApxQkPKeVVU99oOeuzYZb9fwyBH1/b4AEC1UDdFBWwH6rN/MuG17FyBrq/JR64upcM79gITdrIywvd32gYCd+XrGcGIxDoDGufQ1iqjjOihnRdYkYQDhUNEhi3clTz+ZDJ1EqMZmfc+v9Fsnsit2q9wbO3C33Hjbj/gY8AIMOpE7KYGupnpvR+WQk1DvmqiDoIDNfweRvwqF9m+7AUldAxxmjPN0C/WFmYPfZHUFSBK/0+8Ix5pDNw4l3C8thWKeg==
解密后的文本:myEmail@stackoverflow.com

代码:

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("如何拥有自己的公钥以加密数据");
        // 要加密的字符串
        String plaintext = "myEmail@stackoverflow.com";
        // 生成密钥对
        KeyPair keyPair = gerarParDeChaves();
        // 加密
        PublicKey publicKey = keyPair.getPublic();
        String ciphertext = encriptar(plaintext, publicKey);
        System.out.println("密文:" + ciphertext);
        // 解密
        PrivateKey privateKey = keyPair.getPrivate();
        String decryptedtext = decriptar(ciphertext, privateKey);
        System.out.println("解密后的文本:" + decryptedtext);
    }
    public static KeyPair gerarParDeChaves() throws Exception {
        //KeyPairGenerator generator = KeyPairGenerator.getInstance("SHA256withRSA"); // 用于签名
        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"); // 用于签名
        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"); // 用于签名
        Cipher decriptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        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".

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.

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.

Please note that this example code does have no exception handling and is for educational purpose only.

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(&quot;How do I have my own public key to encrypt data&quot;);
// string to encrypt
String plaintext = &quot;myEmail@stackoverflow.com&quot;;
// keypair generation
KeyPair keyPair = gerarParDeChaves();
// encryption
PublicKey publicKey = keyPair.getPublic();
String ciphertext = encriptar(plaintext, publicKey);
System.out.println(&quot;ciphertext: &quot; + ciphertext);
// decryption
PrivateKey privateKey = keyPair.getPrivate();
String decryptedtext = decriptar(ciphertext, privateKey);
System.out.println(&quot;decryptedtext: &quot; + decryptedtext);
}
public static KeyPair gerarParDeChaves() throws Exception {
//KeyPairGenerator generator = KeyPairGenerator.getInstance(&quot;SHA256withRSA&quot;); // used for signatures
KeyPairGenerator generator = KeyPairGenerator.getInstance(&quot;RSA&quot;);
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(&quot;SHA256withRSA&quot;); // used for signatures
Cipher encryptCipher = Cipher.getInstance(&quot;RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING&quot;);
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(&quot;SHA256withRSA&quot;); // used for signatures
Cipher decriptCipher = Cipher.getInstance(&quot;RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING&quot;);
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), StandardCharsets.UTF_8);
}
}

huangapple
  • 本文由 发表于 2020年9月21日 04:00:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63983139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定