Как генерировать CSR на AndroidAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как генерировать CSR на Android

Сообщение Anonymous »

I am developing an Android EST (Enrollment over Secure Transport) client to securely generate and enroll X.509 certificates using mutual TLS (mTLS).
(We need to enroll device with EST protocol instead of SCEP which is less secure, and I didn't found any MDM solution supporting EST)
this is the workflow
1 Generate a Пара ключей на устройстве Android (ECDSA хранится в магазине ключей Android).

2 Создайте запрос на подписку сертификата (CSR) с использованием Bouncycastle.Signal

3 Отправить CSR на сервер MDM). Подпись. На Android недавно ваше понимание будет высоко ценится! < /p>
Заранее спасибо за ваше руководство!package com.example.keygenerationapp;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.security.KeyChain;
import android.security.KeyChainException;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;

import java.io.FileWriter;
import java.security.*;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.util.Objects;

public class KeyGenerationAndCSR {

private static String devicePolicyService;
private DevicePolicyManager devicePolicyManager;
private ComponentName componentName;

public KeyGenerationAndCSR(DevicePolicyManager dpm, ComponentName cn) {
devicePolicyManager = dpm;
componentName = cn;
}

// Generate an RSA key pair and a certificate
public KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048, new SecureRandom()); // 2048 bits for the RSA key
return keyPairGenerator.generateKeyPair();
}

// Method to retrieve the certificate chain associated with the private key alias
public List getCertificateChain(String alias) throws KeyChainException, InterruptedException {
// Using KeyChain to get the certificate chain
return Arrays.asList(Objects.requireNonNull(KeyChain.getCertificateChain(null, alias)));
}

// Create a CSR (Certificate Signing Request) using Bouncy Castle
public PKCS10CertificationRequest generateCSR(KeyPair keyPair) throws Exception {
// Create the certificate subject (e.g., CN=MyDevice)
X500Principal subjectPrincipal = new X500Principal("CN=MyDevice");

// Convert X500Principal to X500Name
X500Name subject = new X500Name(subjectPrincipal.getName());

// Convert the public key to SubjectPublicKeyInfo
PublicKey publicKey = keyPair.getPublic();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

// Use the private key to sign the CSR
PKCS10CertificationRequestBuilder p10Builder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());
PKCS10CertificationRequest csr = p10Builder.build(signer);

// Return the generated CSR
return csr;
}

// Install the certificate associated with the private key in the keystore
public boolean setCertificateForKey(String alias, List certificateChain) {
return devicePolicyManager.setKeyPairCertificate(
componentName,
alias,
certificateChain,
false // Not selectable by the user
);
}

// Save the CSR as a PEM file
public void saveCSRToFile(PKCS10CertificationRequest csr) throws IOException {
try (JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter("csr.pem"))) {
pemWriter.writeObject(csr);
}
}

public static void main(String[] args) throws Exception {
// Simulate the initialization of the DevicePolicyManager and ComponentName objects
DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName componentName = new ComponentName("com.example.app", "com.example.app.DeviceAdminReceiver");

// Create the KeyGenerationAndCSR object
KeyGenerationAndCSR generator = new KeyGenerationAndCSR(dpm, componentName);

// Generate the key and the CSR
KeyPair keyPair = generator.generateKeyPair();
PKCS10CertificationRequest csr = generator.generateCSR(keyPair);

// Save the CSR as a PEM file
generator.saveCSRToFile(csr);
}

private static Object getSystemService(String devicePolicyService) {
KeyGenerationAndCSR.devicePolicyService = devicePolicyService;
return null;
}
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... on-android
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»