下面列出了java.security.cert.CertificateExpiredException#java.security.cert.CertificateException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private TrustManagerFactory createTrustManagerFactory(@Nullable final String trustedCertificates)
throws NoSuchAlgorithmException, CertificateException, KeyStoreException,
InvalidAlgorithmParameterException {
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(PKIX);
if (trustedCertificates != null) {
final KeyStore keystore = keyStoreFactory.newKeystore();
final Collection<? extends Certificate> caCerts;
final byte[] caCertsPem = trustedCertificates.getBytes(StandardCharsets.US_ASCII);
caCerts = X509_CERTIFICATE_FACTORY.generateCertificates(new ByteArrayInputStream(caCertsPem));
long cnt = 0;
for (final Certificate caCert : caCerts) {
keystore.setCertificateEntry("ca-" + cnt++, caCert);
}
trustManagerFactory.init(keystore);
} else {
// standard CAs; add revocation check
final PKIXRevocationChecker revocationChecker =
(PKIXRevocationChecker) CertPathBuilder.getInstance(PKIX).getRevocationChecker();
final PKIXBuilderParameters parameters =
new PKIXBuilderParameters(DEFAULT_CA_KEYSTORE, new X509CertSelector());
parameters.addCertPathChecker(revocationChecker);
trustManagerFactory.init(new CertPathTrustManagerParameters(parameters));
}
return trustManagerFactory;
}
/**
* {@inheritDoc}
*/
@Override
protected Map<AAGUID, Set<TrustAnchor>> loadTrustAnchors() {
checkConfig();
Path keystore = getKeyStore();
try (InputStream inputStream = Files.newInputStream(keystore)) {
KeyStore keyStoreObject = loadKeyStoreFromStream(inputStream, getPassword());
List<String> aliases = Collections.list(keyStoreObject.aliases());
Set<TrustAnchor> trustAnchors = new HashSet<>();
for (String alias : aliases) {
X509Certificate certificate = (X509Certificate) keyStoreObject.getCertificate(alias);
trustAnchors.add(new TrustAnchor(certificate, null));
}
return Collections.singletonMap(AAGUID.NULL, trustAnchors);
} catch (java.security.KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
throw new KeyStoreException("Failed to load TrustAnchor from keystore", e);
}
}
public void checkServerTrusted(X509Certificate[] certificates, String type)
throws CertificateException {
if (this.trustLevel.equals(TrustLevel.OPEN)) {
return;
}
try {
this.standardTrustManager.checkServerTrusted(certificates, type);
if (this.trustLevel.equals(TrustLevel.STRICT)) {
logger.severe(TrustLevel.STRICT + " not implemented.");
}
} catch (CertificateException e) {
if (this.trustLevel.equals(TrustLevel.LOOSE) &&
certificates != null && certificates.length == 1)
{
// If only one cert and its valid and it caused a
// CertificateException, assume its selfsigned.
X509Certificate certificate = certificates[0];
certificate.checkValidity();
} else {
// If we got to here, then we're probably NORMAL. Rethrow.
throw e;
}
}
}
@Test
public void testTrustChain() throws Exception {
final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
));
final AtomicBoolean verified = new AtomicBoolean();
final S3Session session = new S3Session(host, new DefaultX509TrustManager() {
@Override
public void verify(final String hostname, final X509Certificate[] certs, final String cipher) throws CertificateException {
verified.set(true);
super.verify(hostname, certs, cipher);
}
},
new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), host, new DisabledCertificateStore()));
final LoginConnectionService c = new LoginConnectionService(
new DisabledLoginCallback(),
new DisabledHostKeyCallback(),
new DisabledPasswordStore(),
new DisabledProgressListener()
);
c.connect(session, PathCache.empty(), new DisabledCancelCallback());
assertTrue(verified.get());
session.close();
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
SSLContextBuilder builder = SSLContexts.custom();
final String trustFilename = service.getTrustStoreFile();
if (trustFilename != null) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
final String keyFilename = service.getKeyStoreFile();
if (keyFilename != null) {
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
builder = builder.useProtocol(service.getSslAlgorithm());
final SSLContext sslContext = builder.build();
return sslContext;
}
@Test
public void testParseAttestationRecord() throws CertificateException, IOException {
X509Certificate x509Certificate = getAttestationRecord(CERT);
ParsedAttestationRecord attestationRecord =
ParsedAttestationRecord.createParsedAttestationRecord(x509Certificate);
assertThat(attestationRecord.attestationVersion).isEqualTo(EXPECTED_ATTESTATION_VERSION);
assertThat(attestationRecord.attestationSecurityLevel)
.isEqualTo(EXPECTED_ATTESTATION_SECURITY_LEVEL);
assertThat(attestationRecord.keymasterVersion).isEqualTo(EXPECTED_KEYMASTER_VERSION);
assertThat(attestationRecord.keymasterSecurityLevel)
.isEqualTo(EXPECTED_KEYMASTER_SECURITY_LEVEL);
assertThat(attestationRecord.attestationChallenge).isEqualTo(EXPECTED_ATTESTATION_CHALLENGE);
assertThat(attestationRecord.uniqueId).isEqualTo(EXPECTED_UNIQUE_ID);
assertThat(attestationRecord.softwareEnforced).isNotNull();
assertThat(attestationRecord.teeEnforced).isNotNull();
}
/**
* Set the attribute value.
* @exception CertificateException on attribute handling errors.
*/
public void set(String name, Object obj)
throws CertificateException, IOException {
if (!(obj instanceof Date)) {
throw new CertificateException("Attribute must be of type Date.");
}
if (name.equalsIgnoreCase(NOT_BEFORE)) {
notBefore = (Date)obj;
} else if (name.equalsIgnoreCase(NOT_AFTER)) {
notAfter = (Date)obj;
} else {
throw new CertificateException("Attribute name not recognized by"
+ " CertAttrSet:PrivateKeyUsage.");
}
encodeThis();
}
public static PublicKey pem2PublicKey(InputStream in) throws IOException {
try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
Object ohh = pem.readObject();
if (ohh instanceof PEMKeyPair) {
PEMKeyPair kp = (PEMKeyPair) ohh;
return new JcaPEMKeyConverter().getKeyPair(kp).getPublic();
} else if (ohh instanceof SubjectPublicKeyInfo) {
return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) ohh);
} else if (ohh instanceof X509CertificateHolder) {
X509CertificateHolder certHolder = (X509CertificateHolder) ohh;
try {
return new JcaX509CertificateConverter().getCertificate(certHolder).getPublicKey();
} catch (CertificateException ce) {
throw new IllegalArgumentException("Can not read PEM: " + ce.getMessage());
}
} else throw new IllegalArgumentException("Can not read PEM");
}
}
/**
* process the signature block file. Goes through the .SF file
* and adds code signers for each section where the .SF section
* hash was verified against the Manifest section.
*
*
*/
public void process(Hashtable<String, CodeSigner[]> signers,
List<Object> manifestDigests)
throws IOException, SignatureException, NoSuchAlgorithmException,
JarException, CertificateException
{
// calls Signature.getInstance() and MessageDigest.getInstance()
// need to use local providers here, see Providers class
Object obj = null;
try {
obj = Providers.startJarVerification();
processImpl(signers, manifestDigests);
} finally {
Providers.stopJarVerification(obj);
}
}
private void checkTrusted(Func func) throws CertificateException {
CertificateException ex = null;
for (int i =0; i < list.size(); ++i) {
X509TrustManager tm = list.get(i);
try {
func.apply(tm);
// accepted
return;
} catch (CertificateException e) {
if(ex == null || Throwables.has(e, CertPathValidatorException.class)) {
ex = e;
}
}
}
if(ex != null) {
throw ex;
}
}
/**
* Add a name to lookup table.
*
* @param name the name of the attr
* @param oid the string representation of the object identifier for
* the class.
* @param clazz the Class object associated with this attribute
* @exception CertificateException on errors.
*/
public static void addAttribute(String name, String oid, Class<?> clazz)
throws CertificateException {
ObjectIdentifier objId;
try {
objId = new ObjectIdentifier(oid);
} catch (IOException ioe) {
throw new CertificateException
("Invalid Object identifier: " + oid);
}
OIDInfo info = new OIDInfo(name, objId, clazz);
if (oidMap.put(objId, info) != null) {
throw new CertificateException
("Object identifier already exists: " + oid);
}
if (nameMap.put(name, info) != null) {
throw new CertificateException("Name already exists: " + name);
}
}
private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
int length = reader.readInt();
if (length == -1) {
return null;
}
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate[] result = new Certificate[length];
for (int i = 0; i < result.length; i++) {
String line = reader.readLine();
byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
}
return result;
} catch (CertificateException e) {
throw new IOException(e.getMessage());
}
}
public RSAPublicKey getKnoxPublicKey() {
// get the path to the public key
final Path knoxPublicKeyPath = properties.getKnoxPublicKeyPath();
// ensure the file exists
if (Files.isRegularFile(knoxPublicKeyPath) && Files.exists(knoxPublicKeyPath)) {
try (final InputStream publicKeyStream = Files.newInputStream(knoxPublicKeyPath)) {
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(publicKeyStream);
return (RSAPublicKey) certificate.getPublicKey();
} catch (final IOException | CertificateException e) {
throw new RuntimeException(e.getMessage(), e);
}
} else {
throw new RuntimeException(String.format("The specified Knox public key path does not exist '%s'", knoxPublicKeyPath.toString()));
}
}
@Test
public void verify() throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {
Path path = Paths.get("target", "UserV1.esl");
// Path path = Paths.get("target", "2_980_1587284330714.es");
SESeal seal = SESeal.getInstance(Files.readAllBytes(path));
SES_SignInfo signInfo = seal.getSignInfo();
ASN1OctetString cert = signInfo.getCert();
CertificateFactory factory = new CertificateFactory();
X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(cert.getOctetStream());
ASN1EncodableVector v = new ASN1EncodableVector(3);
v.add(seal.getEsealInfo());
v.add(cert);
v.add(signInfo.getSignatureAlgorithm());
Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
sg.initVerify(certificate);
sg.update(new DERSequence(v).getEncoded("DER"));
byte[] sigVal = signInfo.getSignData().getBytes();
System.out.println(sg.verify(sigVal));
}
/**
* Create a certificate using key pair and signing certificate with CA certificate, common name and a list of subjective alternate name
*
* @return signed sever identity certificate
* */
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
List<ASN1Encodable> sans)
throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
NoSuchAlgorithmException, InvalidKeyException, SignatureException {
X500Name issuer = new X509CertificateHolder(_issuerCertificate.getEncoded()).getSubject();
BigInteger serial = getSerial();
X500Name subject = getSubject(commonName);
X509v3CertificateBuilder x509v3CertificateBuilder =
new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
buildExtensions(x509v3CertificateBuilder, publicKey);
fillSans(sans, x509v3CertificateBuilder);
X509Certificate signedCertificate = createCertificate(_issuerPrivateKey, x509v3CertificateBuilder);
signedCertificate.checkValidity();
signedCertificate.verify(_issuerCertificate.getPublicKey());
return signedCertificate;
}
/**
* Add a name to lookup table.
*
* @param name the name of the attr
* @param oid the string representation of the object identifier for
* the class.
* @param clazz the Class object associated with this attribute
* @exception CertificateException on errors.
*/
public static void addAttribute(String name, String oid, Class<?> clazz)
throws CertificateException {
ObjectIdentifier objId;
try {
objId = new ObjectIdentifier(oid);
} catch (IOException ioe) {
throw new CertificateException
("Invalid Object identifier: " + oid);
}
OIDInfo info = new OIDInfo(name, objId, clazz);
if (oidMap.put(objId, info) != null) {
throw new CertificateException
("Object identifier already exists: " + oid);
}
if (nameMap.put(name, info) != null) {
throw new CertificateException("Name already exists: " + name);
}
}
/**
* Validate the cluster CA certificate(s) passed in the given Secret
* and return the PemTrustOptions for trusting them.
*/
protected PemTrustOptions trustOptions(Secret clusterCaCertificateSecret) {
Base64.Decoder decoder = Base64.getDecoder();
CertificateFactory x509 = x509Factory();
PemTrustOptions pto = new PemTrustOptions();
for (Map.Entry<String, String> entry : clusterCaCertificateSecret.getData().entrySet()) {
String entryName = entry.getKey();
if (entryName.endsWith(".crt")) {
log.info("Trusting certificate {} from Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
byte[] certBytes = decoder.decode(entry.getValue());
try {
x509.generateCertificate(new ByteArrayInputStream(certBytes));
} catch (CertificateException e) {
throw corruptCertificate(clusterCaCertificateSecret, entryName, e);
}
pto.addCertValue(Buffer.buffer(certBytes));
} else {
log.warn("Ignoring non-certificate {} in Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
}
}
return pto;
}
public static DatabaseClient getDatabaseClient(String user, String password, ConnectionType connType)
throws KeyManagementException, NoSuchAlgorithmException, IOException {
DatabaseClient client = null;
SSLContext sslcontext = null;
SecurityContext secContext = new DatabaseClientFactory.DigestAuthContext(user,password);
if (IsSecurityEnabled()) {
try {
sslcontext = getSslContext();
} catch (UnrecoverableKeyException | KeyStoreException | CertificateException e) {
e.printStackTrace();
}
secContext = secContext.withSSLContext(sslcontext).withSSLHostnameVerifier(SSLHostnameVerifier.ANY);
}
client = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(),
secContext, connType);
return client;
}
protected PrivateKeyAndCertificate createKeystoreProperties()
throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
try {
keystore.load(filesystem.getInputStreamForRelativePath(pathToKeystore), keystorePassword);
} catch (NoSuchAlgorithmException | CertificateException e) {
throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
}
String alias = keystoreProperties.getAlias();
char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
Key key = keystore.getKey(alias, keyPassword);
// key can be null if alias/password is incorrect.
if (key == null) {
throw new HumanReadableException(
"The keystore [%s] key.alias [%s] does not exist or does not identify a key-related "
+ "entry",
pathToKeystore, alias);
}
Certificate certificate = keystore.getCertificate(alias);
return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
for (X509Certificate certificate : chain) {
certificate.checkValidity(); //检查证书是否过期,签名是否通过等
}
} catch (Exception e) {
throw new CertificateException(e);
}
}
public static CipherTestUtils getInstance() throws IOException,
FileNotFoundException, KeyStoreException,
NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException, InvalidKeySpecException {
if (instance == null) {
synchronized (CipherTestUtils.class) {
if (instance == null) {
instance = new CipherTestUtils();
}
}
}
return instance;
}
public List<X509Certificate> readCertificates(String certificatesFilename) {
try (InputStream certificatesInputStream = getClass().getResourceAsStream(certificatesFilename)) {
CertificateFactory certificateFactory = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE_X_509);
return (List<X509Certificate>) certificateFactory.generateCertificates(certificatesInputStream);
} catch (CertificateException | IOException e) {
throw new SLException(e, e.getMessage());
}
}
@Test
public void testTLSClienAuthNoneAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException,
UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.NONE.name());
configureProcessorSslContextService();
final List<String> messages = new ArrayList<>();
messages.add("This is message 1\n");
messages.add("This is message 2\n");
messages.add("This is message 3\n");
messages.add("This is message 4\n");
messages.add("This is message 5\n");
// Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
final SSLContext clientSslContext = SslContextFactory.createTrustSslContext(
"src/test/resources/localhost-ts.jks",
"localtest".toCharArray(),
"jks",
"TLS");
runTCP(messages, messages.size(), clientSslContext);
List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
for (int i=0; i < mockFlowFiles.size(); i++) {
mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
}
}
private HttpClient openConnection() throws IOException {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (sslContextService != null) {
try {
SSLContext sslContext = getSslSocketFactory(sslContextService);
httpClientBuilder.setSSLContext(sslContext);
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
throw new IOException(e);
}
}
if (credentialsService != null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null),
new KerberosKeytabCredentials(credentialsService.getPrincipal(), credentialsService.getKeytab()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
.register(AuthSchemes.SPNEGO, new KerberosKeytabSPNegoAuthSchemeProvider()).build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(connectTimeout);
requestConfigBuilder.setConnectionRequestTimeout(connectTimeout);
requestConfigBuilder.setSocketTimeout(connectTimeout);
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
return httpClientBuilder.build();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
trustManager.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
defaultTrustManager.checkServerTrusted(chain, authType);
}
}
/**
* Load the collection of CRLs.
*
*/
protected Collection<? extends CRL> getCRLs(String crlf)
throws IOException, CRLException, CertificateException {
Collection<? extends CRL> crls = null;
InputStream is = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
is = ConfigFileLoader.getInputStream(crlf);
crls = cf.generateCRLs(is);
} catch(IOException iex) {
throw iex;
} catch(CRLException crle) {
throw crle;
} catch(CertificateException ce) {
throw ce;
} finally {
if(is != null) {
try{
is.close();
} catch(Exception ex) {
// Ignore
}
}
}
return crls;
}
/**
* Read the trust store off the classpath.
*
* @return handle to inputStream containing the trust store
* @throws CertificateException
*/
private InputStream getTrustStoreInputStream() throws CertificateException
{
InputStream result = ResourceUtil.getInputStream(trustStoreFile);
if (null == result)
{
throw new CertificateException("LdapClientTrustStoreManager.getTrustStoreInputStream file does not exist on fortress classpath" );
}
return result;
}
/**
* Writes an X.509 certificate in base64 or binary encoding to an output
* stream.
*/
private void dumpCert(Certificate cert, PrintStream out)
throws IOException, CertificateException
{
if (rfc) {
out.println(X509Factory.BEGIN_CERT);
out.println(Base64.getMimeEncoder().encodeToString(cert.getEncoded()));
out.println(X509Factory.END_CERT);
} else {
out.write(cert.getEncoded()); // binary
}
}
/**
* Sign assertions in SAML message
*
* @param document
* Document in assertions should be signed
* @param signAlgorithm
* Signature algorithm in uri form, default if an unknown
* algorithm is provided:
* http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
* @param digestAlgorithm
* Digest algorithm in uri form, default if an unknown algorithm
* is provided: http://www.w3.org/2001/04/xmlenc#sha256
*/
public void signAssertion(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
MarshalException, XMLSignatureException, IOException {
try {
if(Thread.currentThread().getContextClassLoader() == null){
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
}
setIDAttribute(document);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//*[local-name()='Assertion']/@ID");
NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
String[] sigIDs = new String[nlURIs.getLength()];
for (int i = 0; i < nlURIs.getLength(); i++) {
sigIDs[i] = nlURIs.item(i).getNodeValue();
}
Init.init();
for (String id : sigIDs) {
signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String ks = System.getProperty("test.src", ".")
+ "/../../ssl/etc/keystore";
String pass = "passphrase";
String alias = "dummy";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(ks), pass.toCharArray());
byte[] cert = keyStore.getCertificate(alias).getEncoded();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream(bout);
byte[] CRLF = new byte[] {'\r', '\n'};
pout.println(X509Factory.BEGIN_CERT);
for (int i=0; i<cert.length; i += 48) {
int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
pout.println("!" + Base64.getEncoder()
.encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
}
pout.println(X509Factory.END_CERT);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
throw new Exception("Should fail");
} catch (CertificateException e) {
// Good
}
}