RSA Verschlüsslung

  • 1 Antworten
  • Letztes Antwortdatum
S

SlayNox

Ambitioniertes Mitglied
15
Hallo Freunde,
ich wollte nur mal eben schnell eine kleinen Grundstein zum Thema RSA Verschlüsslung hochladen.
Damit lassen sich zB API Passwörter oder ähnliches relativ sicher auf dem Gerät ablegen.


Code:
public class RSA {

    private Context mContext;
    private String KEYSTORE_ALIAS;
    private String KEYSTORE = "AndroidKeyStore";
    private String ENCRYPTION_TYPE = "RSA";
    private int KEY_SIZE = 2048;
    private int KEY_LIFETIME = 25;
    private String TAG = "RSA";

    public RSA(Context context){
        this.mContext = context;
        this.KEYSTORE_ALIAS = context.getPackageName()
    }

    public String encryptString (String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableEntryException, KeyStoreException, IOException {
        String encrypted = null;
        byte[] encryptedBytes = null;

        KeyPair keyPair = getKeyPair();

        if (keyPair == null){
            return null;
        }

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
        encryptedBytes = cipher.doFinal(plain.getBytes());
        encrypted = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
        //Alternativ
        // encrypted = bytesToString(encryptedBytes);
        return encrypted;
    }

    public String decryptString (String result) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, CertificateException, KeyStoreException, UnrecoverableEntryException, NoSuchProviderException, InvalidAlgorithmParameterException, IOException {
        String decrypted = null;
        byte[] decryptedBytes = null;
        KeyPair keyPair = getKeyPair();

        if (keyPair == null){
            return null;
        }

        Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
        decryptedBytes = cipher.doFinal(Base64.decode(result, Base64.DEFAULT));
        //Alternativ
        //decryptedBytes = cipher.doFinal(stringToBytes(result));

        decrypted = new String(decryptedBytes);
        return decrypted;
    }

    private  String bytesToString(byte[] b) {
        byte[] b2 = new byte[b.length + 1];
        b2[0] = 1;
        System.arraycopy(b, 0, b2, 1, b.length);
        return new BigInteger(b2).toString(36);
    }

    private byte[] stringToBytes(String s) {
        byte[] b2 = new BigInteger(s, 36).toByteArray();
        return Arrays.copyOfRange(b2, 1, b2.length);
    }

    private KeyPair getKeyPair() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableEntryException, IOException, CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException {
        KeyPair kp = null;
        KeyStore ks = KeyStore.getInstance(KEYSTORE);
        ks.load(null);

        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(KEYSTORE_ALIAS, null);

        if(pkEntry != null){
            kp = new KeyPair(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey());
        }else{
            kp = createKeys();
        }
        return kp;
    }
    private KeyPair createKeys() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {

        Calendar start = new GregorianCalendar();
        Calendar end = new GregorianCalendar();
        end.add(Calendar.YEAR, KEY_LIFETIME);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
                .setAlias(KEYSTORE_ALIAS)
                .setSubject(new X500Principal("CN=" + KEYSTORE_ALIAS))
                .setSerialNumber(BigInteger.valueOf(1337))
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .setKeySize(KEY_SIZE)
                .build();
        final KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(ENCRYPTION_TYPE, KEYSTORE);
        kpGenerator.initialize(spec);

        final KeyPair kp = kpGenerator.generateKeyPair();
        Log.i(TAG, "Es wurde ein neues Schlüsselpaar erzeugt");
       return kp;
    }
}

Der Aufruf sieht wie folgt aus.

Code:
 RSA rsa = new RSA(CONTEXT);
        rsa.encryptString(ZU_VERSCHLÜSSELN);
        rsa.decryptString(ZU_ENTSCHLÜSSELN);

Ich hoffe ich konnte damit manchen etwas helfen!

Liebe Grüße
 
  • Danke
Reaktionen: deek, jogimuc und swa00
Ein kleiner Edit für Android Versionen über und unter Android O

Code:
 private KeyPair getKeyPair() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableEntryException, IOException, CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException {
        KeyPair kp = null;
        KeyStore ks = KeyStore.getInstance(KEYSTORE);
        ks.load(null);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.O){
            PrivateKey privateKey = (PrivateKey) ks.getKey(KEYSTORE_ALIAS, null);
            if (privateKey == null){
                kp = createKeys();
            }else {
                PublicKey publicKey = ks.getCertificate(KEYSTORE_ALIAS).getPublicKey();
                kp = new KeyPair(publicKey, privateKey);
            }

        }else{
            KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(KEYSTORE_ALIAS, null);
            if(pkEntry != null){
                kp = new KeyPair(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey());
            }else{
                kp = createKeys();
            }
        }
        return kp;
    }
 
Zurück
Oben Unten