创建一个密钥对和一个密钥并将它们存储在密钥库中,然后尝试检索对称密钥以将其放入qr码中,但函数 getSecretKey
退货 null
错误代码:java.lang.runtimeexception:无法启动活动组件信息{com.example.securechildlocator/com.example.securechildlocator.createqrcactivity}:java.lang.nullpointerexception:尝试获取空数组的长度。。。在com.example.securechildlocator.createqrcactivity.initqrcode(createqrcactivity。java:49)在com.example.securechildlocator.createqrcactivity.oncreate(createqrcactivity。java:42) ...
public class CreateQRCActivity extends AppCompatActivity {
@BindView(R.id.image_view)
ImageView imageView;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
ButterKnife.bind(this);
creatKeys();
initQRCode();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void initQRCode() {
String qrString = "";
Random r = new Random();
long gruopID = r.nextLong();
String key = Base64.encodeToString(getSecretKey(), Base64.DEFAULT);
qrString = key + ":::" + gruopID;
if(qrString != "") {
StringBuilder textToSend = new StringBuilder();
textToSend.append(qrString);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(textToSend.toString(), BarcodeFormat.QR_CODE, 600, 600);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
imageView.setImageBitmap(bitmap);
imageView.setVisibility(View.VISIBLE);
} catch (WriterException e) {
e.printStackTrace();
}
}
}
private void creatKeys() {
try {
final KeyGenerator skg = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "Android2KeyStore");
final KeyGenParameterSpec secretKeyGenParameterSpec = new KeyGenParameterSpec.Builder("secretKey", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build();
skg.init(secretKeyGenParameterSpec);
final SecretKey secretKey = skg.generateKey();
final KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "Android2KeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
"keyPair",
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setKeySize(2048)
.build());
final KeyPair keyPair = kpg.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
}
public byte[] getSecretKey(){
byte [] secretKey = null;
try {
KeyStore keyStore = KeyStore.getInstance("Android2KeyStore");
keyStore.load(null);
final KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry("secretKey", null);
secretKey = secretKeyEntry.getSecretKey().getEncoded();
}catch (Exception e){
e.printStackTrace();
}
return secretKey;
}
}
暂无答案!
目前还没有任何答案,快来回答吧!