1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2024-06-25 21:14:49 +02:00
pgpainless/pgpainless-core/src/main/java/org/pgpainless/key/protection/UnlockSecretKey.java

56 lines
2.1 KiB
Java
Raw Normal View History

2021-10-07 15:48:52 +02:00
// Copyright 2021 Paul Schaub.
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.key.protection;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.pgpainless.exception.KeyIntegrityException;
import org.pgpainless.exception.WrongPassphraseException;
import org.pgpainless.key.info.KeyInfo;
import org.pgpainless.key.util.PublicKeyParameterValidationUtil;
import org.pgpainless.util.Passphrase;
2021-08-15 15:24:19 +02:00
public final class UnlockSecretKey {
private UnlockSecretKey() {
}
public static PGPPrivateKey unlockSecretKey(PGPSecretKey secretKey, SecretKeyRingProtector protector)
throws WrongPassphraseException, KeyIntegrityException {
try {
PBESecretKeyDecryptor decryptor = null;
if (KeyInfo.isEncrypted(secretKey)) {
decryptor = protector.getDecryptor(secretKey.getKeyID());
}
PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);
if (secretKey.getPublicKey() != null) {
PublicKeyParameterValidationUtil.verifyPublicKeyParameterIntegrity(privateKey, secretKey.getPublicKey());
}
return privateKey;
} catch (KeyIntegrityException e) {
throw e;
} catch (PGPException e) {
throw new WrongPassphraseException(secretKey.getKeyID(), e);
}
}
public static PGPPrivateKey unlockSecretKey(PGPSecretKey secretKey, PBESecretKeyDecryptor decryptor) throws WrongPassphraseException {
try {
return secretKey.extractPrivateKey(decryptor);
} catch (PGPException e) {
throw new WrongPassphraseException(secretKey.getKeyID(), e);
}
}
public static PGPPrivateKey unlockSecretKey(PGPSecretKey secretKey, Passphrase passphrase) throws WrongPassphraseException, KeyIntegrityException {
return unlockSecretKey(secretKey, SecretKeyRingProtector.unlockSingleKeyWith(passphrase, secretKey));
}
}