-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathPEM.java
46 lines (37 loc) · 1.33 KB
/
PEM.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cryptography.encoding.pem;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Base64;
public class PEM {
static String LINE_SEPARATOR = System.getProperty("line.separator");
private static Base64.Encoder encoder = Base64.getMimeEncoder(64, LINE_SEPARATOR.getBytes());
/**
* @param privateKey of EC keypair
* @return elliptic curve primary key in PEM format
*/
public static String ECPrivateKeyToPEMFormat(PrivateKey privateKey) {
return "-----BEGIN EC PRIVATE KEY-----\n" +
new String(encoder.encode(privateKey.getEncoded())) +
"\n-----END EC PRIVATE KEY-----";
}
/**
* @param publicKey of keypair
* @return public key in PEM format
*/
public static String PublicKeyToPEMFormat(PublicKey publicKey) {
return "-----BEGIN PUBLIC KEY-----\n" +
new String(encoder.encode(publicKey.getEncoded())) +
"\n-----END PUBLIC KEY-----";
}
/**
* @param certificate created from key pair
* @return certificate in PEM format
*/
public static String X509CertificateToPEMFormat(X509Certificate certificate) throws CertificateEncodingException {
return "-----BEGIN CERTIFICATE-----\n" +
new String(encoder.encode(certificate.getEncoded())) +
"\n-----END CERTIFICATE----";
}
}